1

I have been trying unsuccessfully to add Drupal behaviors to an existing and workding JS script file that is wrapped in :

jQuery(document).ready(function($){
  // some JS here
  Drupal.behaviors.ios = {
    attach: function (context, settings) {

        // Code to be run on page load, and
        // on ajax load added here

    }
  };
});

I cannot get my behaviours to work.

However I have changed the wrapper to :

(function($){
  // some JS here
  Drupal.behaviors.ios = {
    attach: function (context, settings) {

        // Code to be run on page load, and
        // on ajax load added here

    }
  };
})(jQuery);

and now the behaviours work.

What is the difference between the wrappers and can I expect the existing Javascript to continue functioning if I make this change ?

1
  • When using first approach, did u found any error. It can be issue that, you were getting error in your console when you use first approach, thats why it was not running as expected. Commented Mar 26, 2016 at 12:41

1 Answer 1

1

Drupal attaches behaviours on DOM ready - by waiting until the DOM is ready yourself to actually inform Drupal of your custom behaviour, it's too late (unless you call Drupal.attachBehaviors manually afterwards, which would be less than efficient).

Your 2nd example is both logically correct, and the recommended way to use behaviours with jquery in Drupal 7.

Unless you have a very good reason not to, always using that approach would be a good idea.

2
  • Thanks Clive. Have you any pointers so I can understand the syntax here for the aliasing of jQuery to the $ symbol.
    – elb
    Commented Mar 27, 2016 at 16:58
  • Yes! Read up on anonymous functions and closures, those are essentially what you're dealing with here. I'd recommend searching for both separately too ("js anonymous functions", "js closures"), as it usually takes a couple of different sources explaining it in a couple of different ways for people to take it in
    – Clive
    Commented Mar 27, 2016 at 20:13

Your Answer

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

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