Search code examples
jquerywindow-load

Calling jQuery on (window).load and passing variable for 'No Conflict' code


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?


Solution

  • 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