"Getting started with jQuery and Javascript in Drupal," Geoff Hankerson: Twin Cities Drupal Camp 2011

My second session of day one of Twin Cities Drupal Camp 2011 was “Getting started with jQuery and Javascript in Drupal,” by Geoff Hankerson of Artist Arena.

Here are my notes from the session:


JavaScript helps enhance other things in the browser!

Like in math, we have variables. They have scope: strings (var str), number (var num), boolean (var tof). If your variables are declared at the top of your script, they are global. Be careful about that.

We also have arrays, such as var arr = [’Java’,’Javascript’, ’PHP’];

There are also obhects.

Functions are a group of code statements that are used multiple times. Such as:

function getMessage() { return "anyonymous" };

Very basic. You can also have anonymous functions that don’t have a name. This gets used in jQuery a lot.

Javascript also has plenty of ways to do comparision statements. If then, etc.

To get started, you want to add in the jQuery library as a script tag in the head secion of your document.

Then you can write jQuery statements that will allow you to do awesome things on the page without writing things from scratch.

Important thing to remember is to make sure your jQuery doesn’t start until the page is loaded. This often comes in the form of:

$(document).ready( function() {
CODE GOES HERE
};

That’s an anonymous function, by the way.

There are certain common statements you can then put into that document ready wrapper to make jQuery magic.

Let’s say you have a div with an id of wrapper, set to display none by default. Just add in this within the wrapper:

$(’#wrapper’).fadeIn(3000);

Now that div will fade in on page load. jQuery leverages your CSS knowledge, particularly with selectors. Interestingly enough, if this fadeIn function was attached to, say, a hover behavior, you could make this happen with CSS3 instead. But doing a fadeIn on page load is something that would be difficult to achieve with CSS3. (Feel free to correct me if I’m wrong on that.)

Here’s something else you can add:

$(’p.some_class’).add_class(’lightGray’);

This allows you to add a class to a particular paragraph upon page load. So the appearance can change once the page is loaded.

Here’s another:

$(’a.link’).click( function() {
   $(’#drupal_sites’).slideToggle(’slow’);
});

So we are intercepting the click function for the link and then sliding in a hidden div with an id of drupal_sites, and it will slide in slowly. Pretty slick!

You can see the format coming together. Target a CSS selector, then attach a function to that selected code to do something. This is far easier than trying to write this from scratch in Javascript. Plus, jQuery handles the difficulties in how Javascript is handled in different browsers.

Hovering:

$(’#box’).hover(
  function() {
     $(this).addClass(’boxclass’).stop().animate({
       ’left’: ’300px’
  },
   500
   );
}

This refers to the thing you are hovering over, a div with an id of a box. You can also see here how multiple functions can be chained together. The boxclass is added to the div. Then, we stop, to avoid janky movements if you move over the box multiple times. Then we do an animation that changes the position of the div over 500 milliseconds. Pretty much any CSS property that you want to animate you can put in there. Again, some of these things can now be done with CSS3 Animation. Jeremy Keith spoke at An Event Apart Minneapolis last year about how procedural code like Javascript tends to move into declarative languages like CSS.

Another example:

$(’#drupal_sites li a’).hover)
  function() {
    $(’#box’).text($this).text());
  },
  function() {
   ((’#box’).text(’’);
  };
  

This puts the text from the link into a box when you hover over it.

How do we get this jQuery into our Drupal site?

In the theme info file, you can add a script file with fun jQuery and Javascript statements. This script file will be attached in the head section and functions in here will run on every page.

Since a lot of Javascript files can be generated through modules and themes and such, make sure to optimize JS files on the performance page: this consolidates all your JS files into one file.

In your theme, you can also add a template.php file. You can add Javascript files here as well. This allows you to use the preprocess_page function to evaluate you the path for example and add in JS files on only certain pages.

  function garlandplus_preprocess_page(&$vars) {
  $base = drupal_get_path(’theme’, ’garlandplus’);
  if (arg(0)==’user’){
     drupal_add_js($base.’/js/alert.js’);
  }
  

So this gets the URL for the page when you are using the garlandplus theme. It checks the first argument in that URL (a bit between the slashes), and then it adds a JS file to that page: alert.js.

Another example:

  $node = menu_get_object();
  if($node){
     drupal_add_js($base . ’/js/jquery.dropj.0.0.4.js’);
     drupal_add_js($base . ’/js/jq.js’);
  }
  $vars[’scripts’] = drupal_get_js();
  

This says that if you are on a node page, add certain JS files. For Drupal 6, it’s also important to put in that vars scripts line to make sure the list of JS files gets updated. This is not necessary in Drupal 7.

This specific example added a drop-cap to the first paragraph on a node. It’s an example. But again, this is something that would probably be better to handle in CSS.

In a template file, you can also put in some code to target a particular node nid to add in JS files.

Want to target just the front page of the site? Use the drupal_is_front_page function. You could also create a separate template file, front-page.tpl.ph,p page just for the home page.

I asked if there were any modules out there that allowed you to add a bit of a javascript to the head section of a particular page. Nobody knew of one. This seems like a usability issue to me: it’s not intuitive to go into the template files and write some PHP to target a particular page or set of pages.

I just did a bit of googling, and you can set your input filter on a node to PHP, then use PHP to add a JS file that way. It’s best to put JS in files anyhow, versus inline coding on a page. Still a bit awkward. There are security considerations, of course, but you could lock that down with permissions. If there isn’t a module about this already, it seems like a great opportunity for one to be created.

My take

This was a pretty basic overview of some of the basic principles of jQuery, and how you integrate jQuery with Drupal. There are whole books on jQuery, and you obviously can’t get through all those functions in an hour. So a good intro to get you started!

Archives