Introducing jQuery

Last updated on
1 December 2016

jQuery is a cross-browser JavaScript library, which means it provides some pre-defined functions to make your life easier. Drupal integrates jQuery by default, you can use it in any module or theme without any need to loading it.

The most current versions Drupal 7 is compatible with are jQuery 1.4.2 and jQuery UI 1.8.

This is a short overview of how you can use jQuery. For further guidance see jQuery documentation itself.

Selectors

jQuery makes it easy to select DOM elements. It allows you to very simply "query" the DOM for the set of elements you wish to manipulate using selector. You can also use CSS or xPath selector expression.

Here are some examples of jQuery selector expressions:

CSS selectors

// select all 'a' elements

$('a')
//select the element with the id 'container'
$('#container')
// select all div elements with the class 'ajaxContainer'

$('div.ajaxContainer')
// select all li elements that are the first child of their parent
$('li:first-child') 


X-Path selectors

// select all 'a' elements that have a title attribute
$('a[title]')
// select all 'a' elements whose href attribute begins with 'mailto'

$('a[href^="mailto:"]') 


Custom selectors

// select the second 'li' element

$('li:eq(1)')
// select all odd 'tr' elements that don't contain a 'th' element
$('tr:not([th]):odd')

Commands and effects

Commands is what you can do to your elements once you've selected them.

//hide the element #container
$('#container').hide();

Events

Events correspond to user interaction of some sort, the most obvious being a mouse click. But the loading of your HTML page is also an event, and an extremely important one at that, as we shall see. As for commands, these fall into a few distinct categories, such as commands for DOM traversal, commands for manipulation of DOM elements, effects and AJAX commands.

//when we click on a link inside #menu
$('#menu a').click(function() {
  //display an alert
  alert('Handler for .click() called.');
  //show the element #container
  $('#container').show();
});

Dom ready

Drupal uses its own API "Drupal.behaviors" to do that, please read The Drupal JavaScript API

The DOM elements required won't even have loaded in the page yet by the time this code gets executed, so we need some way of ensuring that it doesn't get executed until the elements it acts upon are ready.

jQuery has a way of ensuring the code gets run as soon as just the DOM has loaded, i.e. just the HTML skeleton of the page, so it doesn't have to wait for large image and media files to load. Here's what it looks like:

$(document).ready(function(){
  // your jQuery code goes here
});