2

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.

5

The 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);
3
  • Direct usage of the jQuery's ready shouldn't be encouraged in Drupal. Behaviors have the advantages of being applied to dynamically updated content and have proper access to settings. Oct 9 '11 at 9:48
  • @PierreBuyle There are cases where the behavior functionality isn't what you want. Fx you only make the code run once per page load. That is why I added it as an alternate example.
    – googletorp
    Oct 15 '11 at 10:25
  • Yep, but your answer doesn't provide any hint on which solution to use on which situation, prompting newcomers to stick with the good old $(document).ready they may already know about. Oct 15 '11 at 10:36
3

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.