Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using '$' instead of 'jQuery' in WordPress

Tags:

jquery

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?

like image 707
Kiran Dash Avatar asked Nov 27 '25 00:11

Kiran Dash


1 Answers

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.

like image 65
eisbehr Avatar answered Nov 29 '25 16:11

eisbehr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!