JQuery is one of the most popular JavaScript libraries on the planet (what is JavaScript). At the time of it's inception, JavaScript (will be referred to as JS from here on in) was in a very different place. January 14th 2006 was the day when jQuery was announced at BarCampNYC. JS was still lacking somewhat -- browsers all supported parts of it, but lots of hacks and workarounds had to be implemented for compliance.

JQuery came along and changed everything. JQuery made it very easy to write browser compliant code. You could animated webpages without having a degree in computer science -- hooray! Ten years on, is jQuery still king, and if you have never it used it before, what can you do with it?

In addition to brushing up on your JavaScript skills, you may want to read some HTML and CSS tutorials first if you are not familiar with them either.

We have introduced jQuery before, so this guide to JQuery will focus on actually coding.

Getting Started

jquery_snippet

You may be familiar with the JS way of selecting ids from the Document Object Model (DOM):

        document.getElementById('foo');
    

Well JQuery takes this one step further. You don't have to call different methods to select classes, ids, or multiple elements. Here's how you select an id:

        $('#bar');
    

Easy right? It's exactly the same syntax to select almost any DOM element. Here's how you select classes:

        $('.baz');
    

You can also get creative for some real power. This selects all td elements inside a table except the first one.

        $('table td').not(':first');
    

Notice how the selector names match almost exactly their CSS counterparts. You can assign objects to regular JS variables:

        var xyzzy = $('#parent .child');
    

Or you can use jQuery variables:

        var $xyzzy = $('#parent .child');
    

The dollar sign is solely used to signify that this variable is a jQuery object, something that is very helpful on complex projects.

You can select the parent of an element:

        $('child').parent();
    

Or the siblings:

        $('child').siblings();
    

You need to execute your code once the browser is ready. Here's how you do that:

        $(document).ready(function() {
    console.log('ready!');
});

More Power

html_table

Now that you know the basics, let's move on to some more complex stuff. Given an html table:

        <table id="cars">
  <tr>
    <th>Make</th>
    <th>Model</th>
    <th>Color</th>
  </tr>
  <tr>
    <td>Ford</td>
    <td>Escort</td>
    <td>Black</td>
  </tr>
  <tr>
    <td>Mini</td>
    <td>Cooper</td>
    <td>Red</td>
  </tr>
  <tr id="fordCortina">
    <td>Ford</td>
    <td>Cortina</td>
    <td>White</td>
  </tr>
</table>

Say you want to make every other row a different color (known as Zebra Stripes). Now you could use CSS for this:

        #cars tr:nth-child(even) {
   background-color: red;
}
html_table_striped

This is how that could be achieved with jQuery:

        $('tr:even').addClass('even');
    

This will achieve the same thing, providing that even is a class defined in CSS. Notice how the full stop before the class name is not needed. These are usually only required for the main selector. Ideally, you would use CSS for this to begin with, although it's not a big deal.

JQuery can also hide or remove rows:

        $('#fordCortina').hide();

$('#fordCortina').remove();

You do not have to hide an element before removing it.

Functions

JQuery functions are just like JS. They use curly braces and can accept arguments. Where it gets really interesting is through callbacks. Callbacks can be applied to almost any jQuery function. They specify a piece of code to run once the core action is completed. This provides huge functionality. If they did not exist, and you wrote your code expecting it to run in a linear fashion, JS would continue to execute the next line of code while waiting for the previous one. Callbacks ensure the code only runs once the original task is complete. Here's an example:

        $('table').hide(function(){
    alert('MUO rules!');
});

Be warned -- this code executes an alert for every element. If your selector is something on the page more than once, you will get multiple alerts.

You can use callbacks with other arguments:

        $('tr:even').addClass('even', function(){
   console.log('Hello');
});

Notice how there is a semi colon after the closing braces. This would not normally be needed for a JS function, however this code is still considered to be on one line (as the callback is inside brackets).

Animation

javascript_animation

JQuery makes it very easy to animate webpages. You can fade elements in or out:

        $('.fade1').fadeIn('slow');

$('#fade2').fadeOut(500);

You can specify three speeds (slow, medium, fast) or a number representing the speed in milliseconds (1000ms = 1 second). You can animate almost any CSS element. This animates the width of the selector from its current width to 250px.

        $('foo').animate({width: '250px'});
    

It's not possible to animate colors. You can use callbacks with animation as well:

        $('bar').animate({height: '250px'}, function(){
    $('bar').animate({width: '50px'}
});

Loops

Loops really shine in jQuery. Each() is used to iterate over every element of a given type:

        $('li').each(function() {
  console.log($(this));
});

You can also use an index:

        $('li').each(function(i) {
  console.log(i + ' - ' + $(this));
});

This would print 0, then 1 and so on.

You can also use each() to iterate over arrays, just like in JS:

        var cars = ['Ford', 'Jaguar', 'Lotus'];

$.each(cars, function (i, value){
    console.log(value);
});

Note the extra argument called value -- this is the value of the array element.

It's worth noting that each() can sometimes be slower than vanilla JS loops. This is due to the extra processing overhead that jQuery performs. For the majority of the time, this is not an issue. If you are concerned about performance, or are working with large datasets, consider benchmarking your code with jsPerf first.

AJAX

Asynchronous JavaScript and XML or AJAX is really very easy with jQuery. AJAX powers a vast amount of the Internet, and it's something we have covered in part 5 of our jQuery tutorial. It provides a way to partially load a webpage -- no reason to reload the whole page when you only want to update the football score, for example. jQuery has several AJAX methods, the easiest being load():

        $('#baz').load('some/url/page.html');
    

This performs an AJAX call to the page specified (some/url/page.html) and shoves the data into the selector. Simple!

You can perform HTTP GET requests:

        $.get('some/url', function(result) {
   console.log(result);
});

You can also send data using POST:

        $.post('some/other/url', {'make':'Ford', 'model':'Cortina'});
    

It's very easy to submit form data:

        $.post('url', $('form').serialize(), function(result) {
    console.log(result);
}

The serialize() function gets all the form data and prepares it for transmission.

Promises

Promises are used for deferred execution. They can be difficult to learn, however jQuery makes it slightly less troublesome. ECMAScript 6 introduces native promises to JS, however, browser support is flaky at best. For now, jQuery promises are much better at cross browser support.

A promise is almost exactly like it sounds. The code will make a promise to return at a later stage when it is complete. Your JavaScript engine will move on to executing some other code. Once the promise resolves (returns), some other piece of code can be run. Promises can be thought of like callbacks. The jQuery documentation explains in greater detail.

Here's an example:

        // dfd == deferred
var dfd = $.Deferred();

function doThing() {
    $.get('some/slow/url', function() {
        dfd.resolve();
    });
    return dfd.promise();
}

$.when(doThing()).then(function(){
    console.log('YAY, it is finished');
});

Notice how the promise is made (dfd.promise()), and it is resolved only when the AJAX call is completed. You could use a variable to keep track of multiple AJAX calls, and only complete another task once all have been made.

Performance Tips

The key to squeezing performance out of your browser is limiting access to the DOM. Many of these tips could apply to JS as well, and you may want to profile your code to see if it is unacceptably slow. In the current age of high performance JavaScript engines, minor bottlenecks in code may often go unnoticed. Despite this, it's still worth trying to write the fastest performing code you can.

Instead of searching the DOM for every action:

        $('foo').css('background-color', 'red');
$('foo').css('color', 'green');
$('foo').css('width', '100px');

Store the object in a variable:

        $bar = $('foo');

$bar.css('background-color', 'red');
$bar.css('color', 'green');
$bar.css('width', '100px');

Optimize your loops. Given a vanilla for loop:

        var cars = ['Mini', 'Ford', 'Jaguar'];

for(int i = 0; i < cars.length; ++i) {
    // do something
}

While not inherently bad, this loop can be made faster. For every iteration, the loop has to calculate the value of the cars array (cars.length). If you store this in another variable, performance can be gained, especially if you are working with large datasets:

        for(int i = 0, j = cars.length; i < j; ++i) {
    // do something
}

Now the length of the cars array is stored in j. This no longer has to be calculated in every iteration. If you are using each(), you do not need to do this, although properly optimized vanilla JS can outperform jQuery. Where jQuery really shines is through the speed of developing and debugging. If you are not working on big data, jQuery is usually more than fast.

You should now know enough basics to be a jQuery ninja!

Do you use jQuery regularly? Have you stopped using it for any reasons? Let us know your thoughts in the comments below!