Working with JavaScript and jQuery

Last modified: February 1, 2009 - 03:36

Using JavaScript adds dynamic presentation effects to a theme. In addition to custom Javascript files many Drupal developers find jQuery useful. jQuery is a lightweight JavaScript library which is built into Drupal. jQuery contains all the common DOM, event, effects, and Ajax functions.

Drupal 6.0 to 6.2 included jQuery 1.2.3. Drupal 6.3 included an update to jQuery 1.2.6, which at the time of writing is the latest version. For use in module development which requires a later version of jQuery, apply the jQuery update module. The jquery.js file is included automatically.

Default JavaScript file

Similarly to style.css, there is a new automatically included file named script.js for adding JavaScript code to a theme. The file should be placed in the theme’s home directory.

JavaScript theming

There is now a theming mechanism for JavaScript code. Together with the automatically included script.js (if no other scripts are defined in .info), this allows theme developers more freedom in the domain of scripted events on Drupal sites. Often, developers use JavaScript code to produce markup that is inserted into a page. However, this may contain HTML that has been hard-coded into the script, which did not allow alteration of the inserted code.

Modules provide default theme functions in the Drupal.theme.prototype namespace. For example, the following code uses the theme function powered (This displays a "powered by Drupal" icon):

Drupal.theme.prototype.powered = function(color, height, width) {
  return '<img src="/misc/powered-'+ color +'-'+ height +'x'+ width +'.png" />";
}

One method for calling this is:

$('.footer').append(Drupal.theme('powered', 'black', 135, 42));

That puts a button like

in the footer.

The following code overrides this in a theme, for example, to include files in a specific theme directory instead of /misc :

Drupal.theme.prototype.powered = function(color, height, width) {
  return '<img src="/sites/all/themes/powered_images/powered-'+ color +'-'+ height +'x'+ width

+'.png" />";
}

This example takes advantage of plain JavaScript. The above function would go in a theme's JavaScript file, avoiding the need for altering the related module's JavaScript files.

JavaScript theme functions are entirely free in their return value. They can vary from simple strings to complex data types like objects, arrays, and jQuery elements. Refer to the original (default) theme function to see what your custom theme function should return.

For more information on using JavaScript and jQuery in Drupal, see the JavaScript section of the developer guide. Also, join the Javascript group on Groups.Drupal.org to get advice on Javascript and jQuery: http://groups.drupal.org/javascript

Still needed: jQuery intro, how to add aggregation (patch at http://drupal.org/node/119441) etc...

 
 

Drupal is a registered trademark of Dries Buytaert.