Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 540
firefusion Avatar asked Dec 17 '11 09:12

firefusion


People also ask

How to avoid jQuery Conflict?

Thus, if you are using another JavaScript library that uses the $ variable, you can run into conflicts with jQuery. In order to avoid these conflicts, you need to put jQuery in no-conflict mode immediately after it is loaded onto the page and before you attempt to use jQuery in your page.

What is window onload in jQuery?

Projects In JavaScript & JQuery The code which gets included inside $( window ). on( "load", function() { ... }) runs only once the entire page is ready (not only DOM). Note: The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0.

Which jQuery function is used to prevent code from running before the document is finished loading?

The Document Ready Event This is to prevent any jQuery code from running before the document is finished loading (is ready). It is good practice to wait for the document to be fully loaded and ready before working with it.


1 Answers

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
like image 186
Rob W Avatar answered Oct 27 '22 17:10

Rob W