I want to run some JavaScript code during the document ready phase.
Where can I place this code so that it runs each time a page is loaded?
I am using Drupal 7.
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityThe easiest solution would be to add the code in your theme. This is done by adding
scripts[] = path/to/file.js
in your theme's .info
file. If for any reason don't want to handle this in your theme, you could instead add the javascript from within a module, using hook_init
function module_name_init() {
drupal_add_js(drupal_get_path('module', 'module_name') . '/path/to/file.js');
}
For the javascript to execute on document ready, you can either use jQuery's ready event, or use a behavior.
This could look like this:
(function ($) {
$(document).ready(function() {
// jQuery's document ready event
});
})(jQuery);
(function ($) {
Drupal.behaviors.name = {
attach: function(context, settings) {
// Drupal's behavior execute on document ready.
}
};
})(jQuery);
You have to define it inside your theme; for a more in depth explanation see Managing JavaScript in Drupal 7, and use something like this inside your JavaScript file:
(function ($) {
Drupal.behaviors.exampleModule = {
attach: function (context, settings) {
$('.example', context).click(function () {
$(this).next('ul').toggle('show');
});
}
};
}(jQuery));
You can also do it from your module.