ruk·si

jQuery
Basics

Updated at 2014-10-27 12:57

jQuery is a general purpose JavaScript library that helps you handle DOM changes, bind events and so on. It's a good library for beginners, but advanced users prefer to pick specific libraries per use case, not use the bloated jQuery.

Run jQuery code only after DOM has been fully loaded. This is less prone to errors.

$(document).ready(function() {
    // ...
});

Don't mix behavior (JS) and presentation (CSS). When you are giving HTML elements classes to be targeted with JavaScript, use a naming schema separate from your normal CSS class naming. The class styles you use to select elements in the document should not have any reference in .css files. I personally use js- to access HTML elements and is- to give additional presentation to JavaScript states.

// bad
$('#modal div:last-child > button:last-child');

// good
$('.js-save-btn');
<!-- bad -->
<div class="box">
</div>

<!-- good -->
<div class="box js-box">
</div>

<!-- after JavaScript acts on it -->
<div class="box js-box is-highlighted">
</div>

Name all jQuery wrapped elements staring $. There are many places where you expect a parameter or return to be a jQuery wrapped object so show your intention.

// bad
var jqueryWrappedCamelCase

// good
var $jqueryWrappedCamelCase;

Use indentation to show structure. Useful when making long method chains with libraries like jQuery. Easier to read.

// bad
$loginArea.find('form').highlight().find('input[name="username"]').update();

// good
$loginArea
    .find('form').highlight()
    .find('input').update();

Keep DOM manipulation to the minimum. Manipulating the page HTML is usually the main thing that causes websites to slow down. Detach elements from the DOM while manipulating them.

var $table = $('#some-table');
var $parent = table.parent();
$table.detach();
$table.addLotsAndLotsOfRows();
$parent.append($table);

Cache your jQuery lookups. Better performance.

// bad
var setSidebar = function() {
    $('.sidebar').hide();
    $('.sidebar').css({
        'background-color': 'pink'
    });
}
$('.list-item').click(function () {
    $('.photo').hide();
});

// good
var setSidebar = function() {
    var $sidebar = $('.sidebar');
    $sidebar.hide();
    $sidebar.css({
        'background-color': 'pink'
    });
}
var photo;
$('.list-item').click(function () {
    photo = photo || $('.photo');
    photo.hide();
});

Use traversal in queries e.g. with find(). Improves performance.

// bad
$('.sidebar ul').hide();
$('.sidebar > ul').hide();
$('.sidebar', 'ul').hide();
$('li:first');

// good
$('#sidebar').find('ul').hide();
$('li').first();

You can use strings to create elements in jQuery.

var $listItem = $('<li>' + reallyLongArray.join('') + '</li>');
$('#the-list').append($listItem);

Learn to use events and prefer using events over callbacks.

// bad
$('a.trigger', $('#container')[0]).live('click', handlerFn);

// good
$('#container').on('click', 'a.trigger', function(e) {
    // ...
});

Use event delegation. Event delegation makes your code less error prone.

// bad, if buttons are added later, they will not work.
$('#filters button').on('click', function() {});

// good
$('#filters').on('click', 'button', function() {});

Prefer adding and removing CSS classes over individual CSS properties. Better performance, easier to change and easier to read.

// bad
$sidebar.css({
    'background-color': 'red',
    'text-weight': 'bold'
});

// good
$('p').hasClass('highlight');       // Returns true/false.
$('p').addClass('highlight');
$('p').removeClass('highlight');
$('p').removeClass();               // Removes all classes.
$('p').toggleClass('highlight');    // Add or remove class.

Prefer using jQuery built-in style functions over CSS properties.

// bad
$secretBox.css({ 'display': 'none' });

// good
$secretBox.hide();