Drupal 101: How to Add Custom jQuery

Full disclaimer here: I love jQuery – I use it all the time. jQuery has made my life as a designer/developer so much better. I use is it on all of my sites – which means I use it within Drupal. When I first got started developing sites with Drupal a few years ago, I remember thinking, “How the hell do I add my own JavaScript?!”. Needless to say, I’ve learned a lot since then.

There are a number of different ways to include jQuery plugins or one-off scripts into your sites/pages. Here’s an overview of some of the ways to do it. The solution you use will likely depend on your workflow or comfort working within the Drupal theme system.

Straight PHP within your node

To use this technique, you’ll need to have the PHP filter module enabled and you’ll need to have access to use this filter within your Page, Blog Post, story, etc. Just create a new node (of whatever type), select the PHP input filter and include the code below (adapted to your needs of course).

<?php

// add js from a module
drupal_add_js(drupal_get_path('module', 'yourModuleName') . '/yourModule.js');

// add inline javascript
drupal_add_js('
  $(document).ready(function() {
    // your custom js here
    $("p.warning").css("color","red");
  });
'
, 'inline');

?>

There are two basic ways to use the drupal_add_js() – You can either use it to include files or to include inline scripts. Above, I’ve show both. The drupal_add_js() function is pretty robust – allowing you to pass along other arguments for changing scope and cache options, but that functionality is outside the, uhhh…scope of this post.

Inclusion within your theme’s ‘.info’ file

This technique is recommended for files that will be used site-wide. Here’s how to do it:

scripts[] = yourScript.js

Note: the paths here are relative to your theme.info file.

Inclusion within your theme’s template.php

I use this technique when I need to add inline jQuery to a single page or to a set of pages. I might do something like this:

<?php
if(drupal_is_front_page()) {
 
drupal_add_js('sites/all/themes/myTheme/js/myScript.js');
}
?>

There’s three ways you can include custom jQuery scripts into your sites. There are other ways (like using hook_init() within a custom module) but I thought I’d save that for another post.

Happy Drupaling.

Comments

Tyler Wolff's picture
How would you suggest adding jQuery from google’s CDN (external js)? Is it possible to just add it to the .info file for the theme? Also, how do you make sure that jQuery is not loaded multiple times, like if a module requires it but loads it from another source (this is similar to registering scripts in wordpress). Thanks!