Web Design

Making javascript play nice in Drupal 7

The task: Put some custom javascript in a file and have it run on a Drupal page.

This is theoretically easy, but I had trouble getting the javascript to do certain things with certain page elements.  Drupal makes it easy to add javascript, but then it sets up a bunch of restrictions.  This is for security reasons and it's a good idea, but it's just one more thing in D7 that is more complicated than it should be.  Anyway, here's the solution:(function($) { // wrapper to make it work with Drupal

(function($) { // wrapper to make it work with Drupal
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    // code starts
    $("#edit-asset-items").click(function() {
      alert("Hello World");
    });
    // code ends
  }
};
})(jQuery);


There are a couple keys here.  First, you need to wrap your code in Drupal.behaviors.myBehavior and attach: function (context, setttings).  Also, tack on an explicity (jQuery) at the very end.  Simple problem, simple solution.

There are, of course, other ways of adding javascript to Drupal, such as drupal_add_js().  But if you want to put your javascript in an external file, this is how.

For more information: https://www.drupal.org/node/171213