renny
renny

Reputation: 203

jQuery error when using $window.load

I have the following code that works inside a document ready event:

jQuery(document).ready(function($) {

    $('tr[data-name="background_colour"] input.wp-color-picker').each(function() {

        //this works
        $(this).closest('tr').siblings('tr[data-type="wysiwyg"]').css('background-color', this.value);

        //this doesn't because frames are not loaded
        $(this).closest('tr').siblings('tr[data-type="wysiwyg"]').find('iframe').contents().find('body').css('background-color', this.value);
    });
});

The background color of the tr is changed successfully but not the body of the iframe because all iframes are dynamically created and they are not fully loaded yet when document is ready.

So I tried using window.load instead as follows:

jQuery(window).load(function($) {

    $('tr[data-name="background_colour"] input.wp-color-picker').each(function() {

        //this works
        $(this).closest('tr').siblings('tr[data-type="wysiwyg"]').css('background-color', this.value);

        //this doesn't because frames are not loaded
        $(this).closest('tr').siblings('tr[data-type="wysiwyg"]').find('iframe').contents().find('body').css('background-color', this.value);
    });
});

But I got Uncaught TypeError: object is not a function on the line below when I did that:

$('tr[data-name="background_colour"] input.wp-color-picker').each(function() {

Got this to work thanks to Guffa's answer. Here is the correct code which might be helpful for other people:

jQuery(window).load(function() {

    jQuery(function($){

        $('tr[data-name="background_colour"] input.wp-color-picker').each(function() {
            $(this).closest('tr').siblings('tr[data-type="wysiwyg"]').css('background-color', this.value);

            $(this).closest('tr').siblings('tr[data-type="wysiwyg"]').find('iframe').contents().find('body').css('background-color', this.value);
        });
    });
});

Upvotes: 1

Views: 784

Answers (1)

Guffa
Guffa

Reputation: 700730

The ready event handler is called with the jQuery object as parameter, but the load event handler isn't.

As you have $ as parameter for the load event handler, it will contain the event object, not the jQuery object. When you try to use the event object as if it is the jQuery object, you will get an error.

Remove the parameter from the load event handler, so that you can access the $ variable from the global scope:

jQuery(window).load(function() {

Upvotes: 3

Related Questions