Reputation: 4956
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'm unable to use $
inside of the window.load
code block. Can anyone help how I can use the $
shortcut inside window.load
?
Upvotes: 2
Views: 351
Reputation: 12452
It's called no conflict mode, and not compatibility mode. To get this working, you have to use a closure
or IIFE
then, only ready states
passes the jQuery object as parameter, load
and others will not do this.
(function($) {
$(window).load(function() {
$('#myid').css({'background': 'black', 'color': 'white'});
});
})(jQuery)
If your load
is already inside a ready state
you can use it directly too (just as example, you should not put a window load
inside a ready state
in general):
jQuery(function($) {
$(window).load(function() {
$('#myid').css({'background': 'black', 'color': 'white'});
});
});
And note that .load()
for such task is deprecated! You should use .on()
instead.
Upvotes: 9