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

Comments

Seriously though - you don't want to do that.  Like I said in my article, security is a big concern in Drupal.  When you start letting people (even trusted admins) insert potentially problematic code in unsanitized locations, you're just asking for trouble.

The best way to load javascript in Drupal is in your .info file or in a custom module function.  For more information: https://drupal.org/node/304255

Pages