4

jQuery included with WordPress is in compatibility mode. To avoid conflicts with other libraries we can not use the '$' shortcut for 'jQuery'.

To use the '$' sign we use:

jQuery(document).ready(function($) {
   $('#myid').css({'background': 'black', 'color':'white'});
});

This works. But my question is how to do the same with window load. I have been facing this problem since last few projects. So, thought better to make the concept clear.

jQuery(window).load(function($) {
   $('#myid').css({'background': 'black', 'color':'white'});
});

With this I get an error that says : "$ is not a function". So, I am unable to use $ inside of the window.load code block.

So, can anyone help how I can use the $ shortcut inside window.load?

2 Answers 2

8

Using a self invoking anonymous function that passes the jQuery object will do the trick:

(function($){ 
   $(window).load(function(){
     $('#myid').css({'background': 'black', 'color':'white'});
   });
})(jQuery); //Passing the jQuery object as a first argument
1
  • 3
    Off-topic note: strictly speaking, this function isn't self-invoking - it doesn't invoke itself, it's you invoking it immediately after defining. Immediately-Invoked Function Expression is a better name IMO.
    – gronostaj
    Sep 27, 2016 at 14:21
1

This is because window load event is different than Jquery load function.

Note also this function can take multiple parameters.

(function(wordpress, $){ 
   $(window).load(function(){
     var emoji = wordpress.emoji; 
     // do somehting with emoji ;)
     console.log(emoji);
     $('body').css({'background': 'black', 'color':'white'});
   });
})(wp, jQuery);

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.