Inserting JavaScript and jQuery into Drupal

In a previous article, I showed how to track comments and contact form submissions using Google Analytics' goals.  The method I described involved adding jQuery.  So I thought I'd take a few minutes to show how to write custom jQuery or other JavaScript and include it on a Drupal page.

One of the nice things about Drupal is that it automatically loads jQuery for you if you include any JavaScript on a given page.  That takes a lot of the hassle of downloading and installing jQuery; it's ready to go.  However, I would recommend that you download and install the jQuery Update module.  This module ensures that your version of jQuery is always up to date.  Installing and configuring jQuery Update is trivial.  Be sure to check the options once you install it.  You can choose whether you want to serve "packed" or "minified" jQuery.  There is a recommendation on the module config page that will give you suggestions.

Next, where do you insert your JavaScript?  In D6, this is very easy.  In your custom theme, you'll want to edit your .info file.  (Be sure not to hack the core themes.  Your custom themes should be in the /sites/all/themes directory.)  This is what my arsnova.info file looks like:

Notice line 63.  That's the line for my custom JavaScript file.  In my theme, that line was already there, just commented out; I uncommented it and kept the default file name of js/script.js.  (My theme was created from Zen, and Zen-based themes have a js/ directory in the theme root.  Your theme might be organized slightly differently.)

Next, you'll want to create a file named script.js in the js/ folder in your theme directory:

Here is my script.js file (used in my article about tracking blog comment form submissions in Google Analytics):

That's pretty much it.  Be sure to empty your Drupal theme cache, and you should be set.

Note: you don't have any control over where this JavaScript loads on your page.  In my Zen-based theme, this loads in the head.  If I were writing tons of JS code, I'd probably opt to load this file near the end of the page.  In order to do that, skip the step about editing your theme's .info file.  Instead, you can edit your theme's page.tpl.php file: