jQuery Logo

How To Add Presentational Javascript to Your Drupal 7 Site

Posted by Art Williams on February 15, 2012

If you want your Drupal 7 site to have a easy user interface with unique effects, you will likely need to add presentational javascript/jQuery to your theme at some point. There are two situations where we might need to add some presentational javascript that each require a different approach:

  • Global: Adding some javascript or a new jQuery plugin that will apply across the entire site.
  • Specific: Adding a snippet of js code that will only apply to a particular view or content type.

Performance and caching

The reason for the varying approaches is to optimize the the performance of the site. If you have javascript that will apply across many parts of the entire site, you only want to load it once and get it cached. If you have a piece of code that only fires on one page, don’t load it up on every page.

Global javascript example

We often pre-fill the global search field with a label (“Search this site”) instead of displaying the label outside of the field. There is a nice jQuery plugin, Example, that accomplishes the task. But to get it to work we need to load the plugin and also our own code to tell the plugin which fields to pre-fill with what text. Clearly this javascript should run on every page on the site.

  1. Place the javascript (plugin and custom) file in your theme folder. We use a /js folder for all javascript files.
    • In this example we upload the jquery.example.min.js plugin file & our custom file that we called fieldtext.js.
  2. Add a line to your .info file for each of the global javascript files.
    • scripts[] = js/jquery.example.min.js
    • scripts[] = js/fieldtext.js
  3. Rebuild the theme registry (drupal url: admin_menu/flush-cache/theme)

Specific javascript example

A common time to need some javascript on only one page of the site is when you have an exposed filter (select list) on a view and you need to alter the first option from the default “- Any -” to something more descriptive. Using jQuery we can use the text() function to alter it.

An example:

$("#edit-field-profile-location-value option:first").text("- Any Location -");

I prefer to have all of my javascript in files in the /js folder inside my theme. Obviously you could include this jQuery in a specific template (tpl.php) file if it already exists, but you don’t have to override the template just for this.

/**
 * Override or insert variables into the html templates.
 */
function yourtheme_preprocess_html(&$vars) {

/*** Ad js files to specific sections of the site ****/
$options = array('type' => 'file');  //tells Drupal that the javascript in drupal_add_js is a file

//Checks if the required string is in the classes array that appears in the body tag on pages created by a view.  Reproduce the following lines for each new section.
if ((in_array('section-profile', $vars['classes_array']))) {
  //Load the js file.
  drupal_add_js(drupal_get_path('theme', 'yourtheme'). '/js/profile.js', $options);
  }
}
  1. Find a body class for the page or section where you want the javascript to run.
  2. Create the javascript file in your theme: js/profile.js in this example because it acts on my profile content type.
  3. To tell Drupal when and how to load this file add a few lines to the yourtheme_preprocess_html() function in your template.php file.
    • If you already have this function then add the code inside at the end of it instead of creating a new function.
  4. Replace “yourtheme” with the name of your theme in the function name and the drupal_add_js line
  5. Replace profile.js with the name of your js file
  6. Replace “section-profile” with the body class you pinpointed in step one.

If you have multiple sections of the site that each need javascript added to just their section, you can repeat these steps for each section and add new if statements to the yourtheme_preprocess_html function

Javascript files

In the files you’ve created with your custom javascript, keep in mind that your code needs to be wrapped in a closure to isolate it from other javascript elsewhere on your site. There are a few different ways to write a closure but I prefer wrapping my code like this:

jQuery(document).ready(function($) {
 
  /*** Your custom code goes here ***/

});

Advanced javascript

There are some more advanced techniques for adding javascript to your site using something Drupal calls behaviors. Behaviors have the potential to be really powerful but are more complicated to get a grasp on than what we’ve gone over so far. If you find yourself needing to reload your javascript each time an AJAX call is made or you are writing a custom module with javascript you should read up on behaviors.

Javascript & jQuery can help make your site easier to use and more interesting to interact with, so I recommend spicing your site up with some nice js touches here and there. Hopefully now you can see how to include javascript code in your Drupal 7 site. If this is all new, give it a try and let us know how it goes. If you are a javascript ninja leave your tips in the comments.

MONTHLY MARKETING INSIGHTS.

Get thought-provoking and actionable insights to improve how your firm makes a connection with your customers.

LEAVE A COMMENT

The content of this field is kept private and will not be shown publicly.

Plain text

  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
Submitted by Emil on Thu, 02/16/2012 - 8:06am

What happens when you aggregate js files later on ?
Wouldn't it merge all js files into one which will be displayed on every page anyway ?

Submitted by JJ on Thu, 02/16/2012 - 8:48am

Thanks for interesting article.
I'd like to see the code you use to display the label “Search this site” in the search box. What are actual JS files I would have to include too?

-jj

Submitted by Art Williams on Thu, 02/16/2012 - 8:52am

@Emil:

You are absolutely correct. If however one of your files is sufficiently large so that you do NOT want it to aggregate you can simply change your $options array to include 'preprocess'=>FALSE


$options = array('type' => 'file', 'preprocess'=>FALSE);

Submitted by Art Williams on Thu, 02/16/2012 - 8:59am

@JJ: The Example jQuery plugin is how I got that to work. I've added a link in the article to the documentation and download.

http://mudge.github.com/jquery_example/

Submitted by JJ on Thu, 02/16/2012 - 9:11am

@art Thanks.
Bit of a newbie and I guess I'm going off topic ... but I was interested in what went into the file you called fieldtext.js ? Are there any other Drupal modules etc that you need to install or enable.

Submitted by Emil on Fri, 02/17/2012 - 3:05am

@Art Williams
Now that makes sense to me:) Thanks for your reply.

Submitted by Art Williams on Fri, 02/17/2012 - 9:01am

@jj: There are no additional modules. In the fieldtext.js file you'll inlude the jQuery statements for the field you want to prepopulate and what text you want inside it. Here is an example for the search block:


jQuery(document).ready(function($) {
 
    /** Form Prefill Example Text ***/
    $('form#search-block-form input.form-text').example('Search this site');

  });

This is a normal jQuery type statement identifying the element using css classes and IDs then executing the example() function which then takes the text as an argument.

The link I posted earlier has extensive documentation on the example() function.

Hope that helps.
-Art

Submitted by JJ on Fri, 02/17/2012 - 2:51pm

@art Perfect - Thanks you

Submitted by roopa on Wed, 07/11/2012 - 3:05am

hey.., i don't know how to add my .js file in drupal7...!
i read the above article.. but as am new to drupal7 i don't how to:
1. find the body-class
2. manipulating "$options = array('type' => 'file');" appropriately for java-scripts
3. also.. i don't know what to do with the below code with-respect-to my java-script file: (my file is "test.js")
if ((in_array('section-profile', $vars['classes_array']))) {
//Load the js file.
drupal_add_js(drupal_get_path('theme', 'yourtheme'). '/js/profile.js', $options);

Kindly help me by replying appropriately... very urgent.... need to launch the website in another 2days...!
Thanks in advance.

Submitted by Amy Peveto on Wed, 07/11/2012 - 10:05am

Roopa, I suggest jumping into the Drupal IRC and asking for assistance there. Info on IRC channels can be found here: http://drupal.org/irc

Submitted by roopa on Wed, 07/11/2012 - 10:30am

okay.. thank you

Submitted by shashank on Mon, 10/08/2012 - 5:49am

Dear Sir,
I am unable to use java script in my Drupal 7.Please sugggest me the method to overcome the problem.
i have installed Drupal 7 and want to add java script in Drupal 7