7th March 2012

How to run Javascript, in Drupal's Admin Overlay, on load

Alli Price
Developer

This is just a small post, but also a cautionary tale. From the moment you start working with Drupal and JavaScript, you'll notice that the awesome jQuery library is thrown in for free. Not only that, but you've also got jQuery UI...

The first thing you learn when starting out with jQuery is:


$(document).ready(function(){
// Your code here
});

In most cases, using this with Drupal will work out fine, but beyond casual theme layer JavaScript there's a better way.

As ever the experts have documented the right thing to do and if you've never seen this page, be sure to give it a thorough read through: http://drupal.org/node/756722

So, our problem. We've got some Javascript we'd like to run on page load, but also have it work within the admin Overlay.

To do this make use of behaviours and attach, as so:


(function ($) {
Drupal.behaviors.exampleModule = {
attach: function (context, settings) {
// This code will run, on load, even in overlay!!!!!!
$('.example', context).click(function () {
$(this).next('ul').toggle('show');
});
}
};
})(jQuery);

That's all that's needed!