0

While using drupal 7, is it necessary for to wrap pure javascript code with jquery wrapper? (I understand that while working with jquery, I need to wrap my code inside beaviors.)

code

function openWin()
  {
    mycode     
  }

od should I wrap it like this

(function () {

function openWin()
  {
mycode
  }

  })();

Or even use behaviors? Thank you.

1 Answer 1

1

You don't have to wrap your code with a behavior or jQuery at all. That depends:

If you want to use jQuery object with the $ as a shorthand:

Wrap your code like this:

(function($){
  //$('#something').show();
})(jQuery);

If you want to execute something after an Ajax DOM change and on document ready event

Use behaviors.

Drupal.behaviors.ysu_premium = {
  attach: function (context) {
    //jQuery('#something').show();
}}

You can wrap the behavior with the above jQuery wrapper if you want to use jQuery.

(function($){
  Drupal.behaviors.something_unique = {
    attach: function (context) {
      //$('#something').show();
    }}
})(jQuery);

When I'm working on Javascript, I always use the last snippet above.

2
  • Hi, In you examples you used jquery code right? I wanted to use javascript code. I tried to put code inside (function () {... but id did not work. So i put only plain jquery code like function openWin() { var myWindow=window.open('','','width=200,height=100'); ... and it works. So I am confused a little:)
    – loparr
    Commented Dec 5, 2014 at 20:10
  • The snippet in your above comment is not using jQuery, so you don't need to wrap it as shown above.
    – AKS
    Commented Dec 5, 2014 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.