2

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?

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.