7

I recently learnt, the very handy trick, that lets you pass the $ in the jQuery function so that you all the contained code is in a No Conflict mode. The advantage being that you can write all the contained code with the '$' instead of 'jQuery'.

This code works fine...

jQuery(document).ready(function( $ ) {
// My code
});

This code does not work...

jQuery(window).load(function( $ ){
// My code
});

It says '$ is not a function'. How to I get it to work?

firefusion
  • 1,087
  • 2
  • 14
  • 26

1 Answers1

15

Create an (anonymous) self-invoking function, and pass the jQuery object as shown below:

(function($){  //This functions first parameter is named $
   $(window).load(function(){
       // Your code
   });
})(jQuery);    //Passing the jQuery object as a first argument
Ilya Suzdalnitski
  • 52,598
  • 51
  • 134
  • 168
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Why is this required? And should you always use this, even when using document.ready in no-conflict mode? – jjeaton Feb 08 '13 at 15:26
  • 3
    @jjeaton By using a closure as shown above, you are 100% certain that `$` inside that function always refers to the jQuery object at that time (otherwise, `$` might be overwritten at a later point, causing an unpredictable error). The actual problem in the question is that the OP assumes that `$` in `.load(function($) ... )` is a jQuery object (which is not - see the documentation of [`.load()`]()http://api.jquery.com/load/). The first example works, because it's actually a documented feature of `.ready`, again read the documentation: http://api.jquery.com/ready/ – Rob W Feb 08 '13 at 18:13