0

On my Drupal site, I have a simple jquery file attached to the theme. This file is added in preprocess_node. The whole content of the file is as follows:

(function ($) {
  console.log("hello world");
  $('li').addClass('hello');
  $('div').addClass('hi');
})(jQuery);

Here is what happens when I run any Drupal page:

  1. no javascript errors
  2. the console shows "hello world "
  3. in Chrome debug, div's do not have class "hi" and li's do not have class "hello"

I ran the same (without wrapper function) on jsfiddle for some basic html and the result was as expected, classes were added to div's and li's and can be seen in Chrome debug. So why is it not working in Drupal?

1
  • 1
    Are you running this javascript AFTER the page has loaded and the DOM elements are present? If not, then you either need to move the javascript to be after the HTML or use $(document).ready() to make the code wait until the DOM is ready. jsFiddle defaults to only running your javascript code after the page has loaded which could explain why it works in jsFiddle.
    – jfriend00
    Jul 15, 2012 at 9:06

1 Answer 1

5

You need to utilize Drupal's JavaScript Behaviors functionality in order to ensure that your javascript is run after the DOM has loaded and that it will not conflict with other javascript in Drupal.

Try changing your JS file's code to this:

(function ($) {

Drupal.behaviors.myModuleBehavior = {
  attach: function (context, settings) {
    console.log("hello world");
    $('li').addClass('hello');
    $('div').addClass('hi');
  }
};

}(jQuery));
1
  • IT's working with these settings.
    – camcam
    Jul 15, 2012 at 23:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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