Friday. Log Out! Shut down! Get out!

So you just started with jQuery

January 15, 2013by Andrei Dragomirin DevelopmentNo Comments
jquery_logo

Good for you! It is one of the best JavaScript libraries out there. It resolves most cross-browser issues and provides methods for common client-side programming tasks, which would have taken you a lot of time (and skill) to implement back in the old days. It really is a time-saver.

Nevertheless, there are a few things to keep in mind when using jQuery, which will reduce the chances of bugs to slip through and will improve the performance and readability of your code.

Use an anonymous wrapper

Polluting the global namespace in JavaScript is a bad thing. But you can easily avoid this. Just wrap all your code in a self-calling anonymous function.


// set the '$' free for other libraries
jQuery.noConflict();

(function($) {
    // Your code
    // You can safely use '$' instead of 'jQuery' here
})(jQuery);

Modules

Keep your code grouped by functionality. It’s cleaner this way and way easier to debug.


var SliderWidget = function() {
    // all the code belonging to the slider
}

// Run the modules after the Dom is loaded.
// You can easily switch a module on or off here
// by commenting out a line during development
$(function() {
    SliderWidget();
    AnotherWidget();
    SomeAwesomeFunctionality();
});

Caching

You may be tempted to overuse the $ constructor. Don’t.

jQuery does a lot of stuff to build an object for a given selector. It does not make sense to rebuild the object every time you need to use it.


// BAD
$('#search-form input:text').focus();
$('#search-form input:text').addClass('focus');
$('#search-form input:text').keyup( function(e) {
    // do something
});

// BETTER
var searchBox = $('#search-form input:text');
searchBox.focus();
searchBox.addClass('focus');
searchBox.keyup( function(e) {
    // do something
});

// EVEN BETTER WITH CHAINING
var searchBox = $('#search-form input:text');
searchBox
    .focus()
    .addClass('focus')
    .keyup( function(e) {
        // do something
    });

Event delegation

Imagine a page containing a movie watchlist. An autocomplete field adds movies to the list, each movie item containing a poster, a title and some text, and a “Watch trailer” button.

var watchList = $('#watchlist'),
    autocompleteResults = $('ul.autocomplete-results');

$('#watchlist-form input:text').keyup( function(e) {
    // code to populate result list
    // then
    autocompleteResults.find('li.result').click( function(e) {
        // append a movie item to watchList
        // then
        $('a.trailer-popup-button').click( function(e) {
            // show a modal window with the trailer
        });
    });
});

First, avoid binding event handlers inside other event handlers. In this example, every time you click on an autocomplete result, besides appending a movie item to the list, you attach the same behavior to all the trailer popup buttons again.

So when you add a second movie, the trailer button of the first movie will fire twice. If you add another movie, the same button will fire three times, showing 3 popups with the same content, and so on. You don’t want that.

A good solution is to use event delegation (which can also be applied to the autocomplete results). The code would then look like this:

var watchList = $('#watchlist'),
    autocompleteResults = $('ul.autocomplete-results');

watchList.on( 'click', 'a.trailer-popup-button', function(e) {
    // show a modal window with the trailer
    // and to prevent the browser to follow the link in the href attribute, never forget:
    e.preventDefault();
});

autocompleteResults.on( 'click', 'li.result', function(e) {
    // append a movie item to watchList
});

$('#watchlist-form input:text').keyup( function(e) {
    // code to populate result list
});

It looks much better now, but most important, it works as it should.

Don’t overuse it

It’s great that jQuery does a lot of stuff for us. But sometimes we just have to think of performance. Vanilla JavaScript will always be faster than any library.

$('#watchlist-form input:text').keyup( function(e) {
    // get the input string
    var q = $(this).val();
    // but instead you could simply do:
    var q = this.value;
    $.get( autocompleteURL + '?q=' + q, function() {
        // populate the result list
    });
});

This may not be a great improvement, performance-wise, but you get the idea.

***

These are just a few things to consider when building pages rich in interaction elements, but they will surely help until you enrich your set of skills and best-practices.

Don’t hesitate to drop a question in the comment form, or share any improvements you would bring to the above approaches.

Tags:

Andrei Dragomir

Andu is all for the money, fame and glory :). Just kidding, because he’s involved wherever he can find quality, challenges, progress, trust and creativity.

He hates the flaws of humanity like upstartness and shallowness and also...the huge numbers of cars in the world.

A nature lover, he likes trekking and catching dawn at an outdoor music festival. Being a casual guy, he thinks that minds should always be open and people should leave, more often, formalities aside.

What do you think?

*