# Introduction to JS and Jquery

Javascript (JS) is a scripting language. It is commonly used to enhance web pages to add interactivity and a deeper user experience. It has been around from 1995 in Netscape and has seen a huge rise from the creation of jquery in 2005. Originally named Mocha, later renamed to LiveScript, and then to JavaScript after a license agreement between Netscape and Sun. Its connection to the common coding language Java ends there (for those wondering).
Differently from php, that is processed by the server behind the web site, JS can be seen in the source code of any web site, if present (Right click -> view source code), and is executed by the browsers on the client-side.
More explicitly, the Javascript is a clever way to interact with the Document Object Model (DOM), which is an abstract representation of the HTML nested-tags structure.

### Fundamentals

I won’t go over the full JS syntax (you can look it up online), but its mostly similar to standard coding languages like C or Java (use parentheses for if conditions and curly brackets to define functions etc.).
What is worth mentioning are however, some particularities:
First and foremost, JS is a loosely typed language, its variables type must NOT be declared, and in most cases JS will do the conversion work for you.
Semi-colons (;) after instructions are required, but for some operations they are not. Please ensure that you always put all the semicolons where they belong otherwise you could have trouble sneaky bugs driven by missing “;”. This is exacerbated by the fact that, being a client-side executed scripting language, it does not show explicit errors like you would expect from a C code. A semi-colon missing on a C language will throw a big error upon compiling, one missing in Javascript will simply stop all the rest of the script without apparent notice.
This brings us to the JS console, which is your main tool of debugging. First, you will mostly do your debugging in a browser since its there that the code is executed.
Every browser has a JS console, just look it up in the Show panel for something named like that. Learning shortcuts to call it is useful too (e.g. in Chrome with a Mac computer is called by Cmd+Alt+J )
If any error shows up, it will be sent out to the console, along with the line number
A JS script is inserted into an HTML file by including in the <script> tag.
With older browsers a script type attribute (with value “txt/javascript”) was necessary, but it is now mostly safe to simply put your code into a plain <script> tag, like in the image above.
If you want to try some of the code while reading, I suggest using JSfiddle, it allows you to rapidly test what you are learning.
(JSfiddle tip: in the HTML section if you write ‘doc’ and hit TAB, it will create a minimal HTML structure to play with, without having you to rewrite the htmlheadbody tags every time you want to fiddle along. The HTML version and eventual JS libraries can be imported from the respective drop-down menus and are included implicitly, this is why you won’t see any <!DOCTYPE HTML>, but remember that it is best to put it should you write your own site)

### How can I debug my code?

The straightforward way to debug your code in any language is to print up important variables’ values in certain points, and JS makes no difference. The equivalent of print statements in JS is console.log(message), or a more aggressive alert(message).

console.log("Hello World!");
alert("Everyone stops and listen to me!");
console.log("I won't be showing in the console until you deal with the alert");

The console.log instruction will print out whatever you give it as argument to the console, while the alert will stop whatever the browser is doing and pop up an alert window until you click it.
You can try to insert these statement in the debugging console (it is interactive) of every browser if you want to get a rapid grasp of what is going on.
The next bit will show you a bit of code that contains an error and how the browser handles this. The only other thing you have to know is that, in JS, when you write a string, it does not matter if you use single quotations (‘) or double quotations (“), as long as you are consistent with them. I can write “Hi there” or ‘how you doin’ (implying Joey from FRIENDS can code) but I cannot write “Fine, thanks’.

If you run this, you will see how the only alert that shows up is the last one.

### How can we insert JS?

There are three main ways to insert a JS script:

• By using a <script> tag as shown above
• By inserting it inline in certain attributes

There is not a preferred way to insert JS into your HTML, yet some could be more useful in certain situations (e.g. writing a big page, you could keep the JS separated from the HTML to avoid having too many lines and prepare yourself for a hard-time with debugging).
A typical way to insert the code inline is by using event attributes, like the <a> onclick:

There are 3 things to explain here:

The hash “#” in the href attribute stands for “move at the top of the page”. We put it just to create a quick hyperlink, but instead of bringing you up top, we just want it to work as a button: the return false in the onclick part does exactly that, suppressing the standard behaviour of the <a> tag. That onclick can be filled with JS, in fact you can see how there is a console.log() and the previously mentioned return false.

The fact that the two instructions are written in the same line has no special meaning: Javascript ignores the positioning and the indentation of the code, since it simply parse each semi-colon-separated instruction.

### Variables and Functions

Let us now talk about variables. We specify a new variable with keyword var (untyped, remember?), followed by a valid variable name. A valid variable name can begin with any lower/Upper-case letter, or even with the dollar sign ($). Remember this because the part on jquery later on will require this information. The var keyword can be omitted to declare global variables, that is, they can be accessed from everywhere in the code. Functions are instead defined by the keyword function that can be followed by the name of function (not required though), arguments, and the code block. If we create a global variable inside a function, it will be available outside the function too and this is something we usually want to avoid. In JS function definition is an operation that returns the function itself, this means that we can define a function and assign it to a variable. This behaviour is called having first-class functions. var$validVariable;
var stillValid = 42;
var 3dent; // THIS IS NOT VALID!
return a+b;
}
scream = function () {
console.log("AAAAGH!");
}
scream();


In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures.

Let’s see an example of a function assigned to a variable.

To understand this example we have to add some more concepts:
First the keyword this, it is a concept borrowed from the object-oriented programming. We can create a function that has attributes and methods, in this case we have x (attribute, static information), and party (a function, an action that we can do). Think of the whole function partyAnimal as a blueprint for all party animals we can create. If you have a blueprint for something (say, a radio), you can create many of those radios, with the same underlying attributes (volume, FM station, power state) and methods (turn up/down the volume, move to another station, on/off) but the single instances (or single radios) will have, at any given time, different values for those attributes. This concept is brought up to the code by the possibility of defining a class with attributes (e.g. variables) and methods (e.g. functions), that can be instantiated how many times I want.
With the this keyword, I specifically refer to the attribute or method of the currently istantiated partyAnimal.
But defining the function is just writing out the blueprint, the way to instantiate (and thus create a realization of the “project”), is the keyword new. Do not worry if you can’t grasp this all at once, it is perfectly normal to be startled by first-time approaching object oriented-programming. It will come with time.
Getting back to our partyAnimal, we create a new partyAnimal() and assign it to a variable (in this case an). Now we can access its attributes and methods with a dot: an.party() calls the method party defined in the blueprint. In a similar fashion we could call an.x to access the x attribute.
If you haven’t seen it anywhere else yet the line stating

this.x == 1 ? console.log("so far: " + this.x + " party") : console.log("so far: " + this.x + " parties");

uses a ternary operator, which is short-hand for a if-else statement. It asks: “is this.x == 1 ?”, if yes do the first instruction, else do the other one (the instructions are separated by the colon “:“). In this case it is just used to handle plurals.

### Operators arithmetic

The “+” operand can mix various type of data, for example we can create a string by summing a string with a number, to provide information in a console.log:

var answer=42; console.log("The answer is " + answer);

yet we must be careful with this automatic type conversion since it can lead to undesired behaviours:

"43770" + 1337 // outputs "437701337"
("323" * 1) - 23 // outputs 200

this is because the string multiplication is not defined and the predefined action for string * int is to try to convert the string into a number.
The “-” operand is not defined for strings, but if a string resembles a number, it tries to convert it and do the standard number subtraction:

"hello" - "o" // returns NaN
"100" - "10" // returns 90

Other available operands are :

• “%” (modulo operation, that is the remainder of the division between the two operands, it can be useful to determine if something is odd or even).
• “==” equality
• “===” strict equality (that is, without type conversion)
• their counterparts “!=” and “!==”

NaN is worth mentioning: it stands for Not a Number, and it is the standard output of impossible operations (e.g. division by zero). It is sticky, that means that every operation involving a NaN will return a NaN.

## DOM manipulation

Let us now dive more into the real page manipulation. As we said earlier, the DOM is a representation of the nested-tags structure of the HTML page. JS provides a variable named document to access the DOM, and a series of methods to access the objects in the page.

In this example we created a list that gets updated with a new element each time we click on the More anchor. In particular we told the anchor to fire the add() function that we defined below in a separated script.

1. It calls document.createElement(‘li’) and assigns it to a variable x. This method creates a <li> tag which is not put anywhere yet, it just exists. For now it is stored in x.
2. Then we can call the attributes (see? no parentheses) to define the properties of this newly created tag <li>. “className” intuitively adds a class=”list-item” to the tag while “innerHTML” controls what is between <li> and </li>, in this case a String.
3. Then we take the list that is already in the HTML and we “append” our new <li>. This is done by selecting the ul list by referring to its Id (document.getElementById(‘list’)) and then by calling its method appendChild(x). The word “child” refers to elements within the parent tags, in this case the <ul>s. Appending is the processing of putting the x after the last existing element.
4. Increment the counter (which is a global variable).

The class attribute is useless in this example, but we can readily make use of it by using different colors for odd and even elements.

The document variable’s methods are many, and it does not hurt to know some of them, especially if you happen to stumble in code written by others. However, in 2005, a guy named John Resig invented jQuery, and simplified the life of many front-end developers.

## jQuery

jQuery is a JS library which gives you one great tool: the “$” function. Import jQuery just like you would with any other JS script, with the src attribute (you can download it) or href if you want to use online versions. Then, for selecting the object in your page we just call: $(selector)
Where selectors follows the basic css rules (“#Id”, “.class”, etc.) plus something more that we can rapidly check in the docs.
Once we have our element we can call intuitive commands for interacting with the DOM, like:

• .css() to modify the style of the element
• .toggle() to show/hide the element
• .click() to define what happens when it gets clicked
• … and many others (please refer to the jQuery docs for all the options or here to see it in action)
• They are chainable! (i.e. we can write $(selector).method1().method2().etc.etc ) Let’s recap some of the features that make jQuery unique: • JS accepts variable names starting with “$”. jQuery “$” is just a function name. All jQuery script does is defining that function (with a lot going on inside the functionnevertheless, but it is still only one function). • First-class functions make it possible to store any instruction in a variable. It is perfectly legal to both write x =$("#divId"); x.css('background-color','red');
or
 $("#divId").css('background-color','red'); • Selectors and methods are more intuitive than DOM standard manipulation methods (e.g. document.getElementById(‘id’) gets replaced by$(‘#id’) ).

### Showcase: some selectors

$(“#button”) <- element with “button” Id$(“ul li:first”) <- first li of the first ul
$(“ul li:first-child”) <- the first li of each ul$(“[href]”) <- all elements with an href attribute
$(“a[target = ‘_blank’]”) <- all anchors with a target attribute equal to “_blank”$(“tr:even”) <- all even table rows

### Events

jQuery handle the events in a very elegant way. Each methods that is related to an event (See this page for a comprehensive list) attaches a “listener” on that object that waits for the event to occur and then fires up what is called a callback function

This time I used the lower part of JSfiddle so I could include jQuery (by clicking in the drop-down menu).
Take a look at the notation: we first select the button with its Id, then call the click function (which is an event handler), and give the click function another function as an argument. This latter function is the callback, that is what gets executed everytime the event occurs, not before nor after. We are delving into the realms of asynchronous functions but for now, let’s just learn how the callback works, and how you use it in jQuery to make things disappear.
A perfectly equivalent version would have been

or

This structure is common to all event handlers, so we won’t be covering up the others, just remember that:

• the event handlers fires the callback function everytime the event is triggered
• the callback function can be defined inplace or outside, it does not matter.

### Showcase: some event handlers

.click() <- when the element gets clicked
.change() <- when the element changes (e.g. a form gets filled)
.hover() <- when the pointer passes over the element
.on() <- generic event handler, we can define multiple behaviours for multiple events

### Gets

With jQuery, we can get and modify text inside the tags as well. These methods have a common structure, that is, if called without arguments they return the current value, otherwise they modify the element according to the argument passed.

 $(selector).html() //returns the html of the element$(selector).html("Hello World!")
//modifies the selected element's HTML into "Hello World!"

These methods are straightforward: call them without arguments and you have a “get” behaviour, returning the current value of what you asked, or with arguments and you have a “set” behaviour, modifying the called element.

### Showcase: some “get/set” methods

.val() <- Get/set values in forms
.text() <- Get/set the combined text contents of each element in the set of matched elements, including their descendants
.html() <- Get/set the HTML contents of the first element in the set of matched elements
.attr(attributeName) <- Get/set the attribute of the selected element. For a “set” behaviour, add another argument with the new attribute value e.g. $(‘#myAnchor’).attr(‘href’,’www.ILoveJS.com’) Remember that with JS you can always chain the instructions. In this way you can one-line your way to front-end olympus. $('#myAnchor').attr('href','bioinformationx.com').text("Go to this awesome site!")

### Selecting multiple elements

You may have guessed from previous hints that selectors are not always unique. A simple class selector usually yields more than one element. Applying the previous methods to a multiple selector have different behaviours depending on the method itself (you should look at the docs for each case you are interested in), but the standard one is that of applying the action only on the first matching element, so keep this in mind.
One way to deal with selectors of multiple elements is to apply the same function to all elements, with the method .each(). The syntax of each is something you have already seen, a function. The only thing to be careful though, is that how you actually refer to the single element inside the each-called function.

$('.aDiv').each( function() { //select all the elements with class aDiv$(this).html("<span>;You have been visited by the tooth fairy</span>;");
});


The keyword this came back! In this case it is the only way to refer to the elements selected by the .aDiv selector, and the each function will take care of applying that function one-by-one: it knows who this refers to.

Up to now you have seen the JS scripts put inside an almost empty HTML or in a special section of JSfiddle which corresponds to an external file. Normally, in a more structured web page, you should put your JS at the end of the HTML to be sure that all elements that it refers to are loaded (otherwise it could try to select a not yet-existing div and throw an error).
jQuery simplifies this aspect by providing the ready function, which is a method of the document variable, it requires a callback function which gets executed when all the rest of the document is loaded. That is, you don’t have to worry where to put your JS code. If it pleases you you can put it in the <head> tag too, as long as you execute all your JS inside the callback function of document.ready()
An example:

where in this case the jQuery library has been imported directly from a downloaded file. This code makes the paragraph blue, although the JS part is written before it. Try it (not in JSfiddle because you cannot load your own libraries).
The less obvious aspect of the document.ready method is for ensuring that everything, especially in contexts where there are a lot of scripts or a lot of images involved.
Beware though, that not everything that’s JS needs to wait for the document to load entirely, but we won’t talk about this here. (You can go here for some more perspective, but for now it’s ok not to completely understand when to use it and when not).

### TableSorting with TableSorter

One of the wonders of jQuery is that it allowed the building of many useful libraries (see again this link in jqueryui to get a look at some of the possibilities). Here you will see a simple application to have a dynamical table with sortable rows.

1. Build a jQuery identifiable table (use an Id, e.g. “myTable”);
 $("#myTable").tableSorter(); And your table is sortable! You can specify which column define the starting sort if you want by passing the tableSorter method an associative array with a key called sortList and a value of a multi-array containing column numbers (in order of priority) and a 0/1 for descending/ascending sorting. $("#myTable").tableSorter(
);