Not a Drupal specialist, but this blog entry suggest that, as of Drupal 6, you don't need to include the $(document).ready()
function in our jQuery code at all.
Instead you could put all the code inside a function that you assign as a property of Drupal.behaviors
.
In the misc/ directory
of the Drupal install, we not only have the jquery.js file but we also have drupal.js (and several other js files, controlling functionality specific to certain pages or admin features, e.g. upload.js), which governs the general use of jQuery in Drupal.
It declares the Drupal JavaScript object for the purpose of containing properties that need to be accessed and used by other js files. For example, the Drupal.settings property is used for passing an array of module settings to the js code for that module. You do this simply by calling drupal_add_js() in your php code and making sure the second parameter is passed in as "setting", e.g.:
drupal_add_js(array('mymodule' => $array_of_settings), 'setting');
In your js file, then, you can access these settings at Drupal.settings.mymodule. You have thus extended the Drupal.settings object with the mymodule property, which is itself an object containing all your settings.
Another property of the Drupal object is the behaviors object, i.e. Drupal.behaviors
, and when we want our module to add new jQuery behaviours, we simply extend this object. The entire jQuery code for your module could be structured like this:
Drupal.behaviors.myModuleBehavior = function (context)
{
//do some fancy stuff
};
But, you may wonder, all that does is declare a function - how does it even get called? Well, that's all looked after in drupal.js. It has a $(document).ready
function which calls the Drupal.attachBehaviors
function, which in turn cycles through the Drupal.behaviors
object calling every one of its properties, these all being functions declared by various modules as above, and passing in the document as the context.
The reason for doing it this way is that if your jQuery code makes AJAX calls which result in new DOM elements being added to the page, you might want your behaviors (e.g. hiding all h3 elements or whatever) to be attached to that new content as well. But since it didn't exist when the DOM was loaded and Drupal.attachBehaviors
ran it doesn't have any behaviors attached. With the above set-up, though, all you need to do is call Drupal.behaviors.myModuleBehavior(newcontext)
, where newcontext
would be the new, AJAX-delivered content, thus ensuring that the behaviors don't get attached to the whole document all over again. See here for the full example of how to use this code