Rain
Rain

Reputation: 139

window.onload in jQuery

I have use the example of sizzle and there I got window.onload in the last of the code.

What does this means.

My code is like this:

var init = function () {
    var trail = Sizzle;
    var foo = trail('.foo');
    foo[0].onmouseover = function () {
        this.style.backgroundColor = (this.style.backgroundColor.indexOf('blue') === 0) ? 'yellow' : 'blue';
    };
    foo[1].onmouseover = function () {
        this.style.backgroundColor = (this.style.backgroundColor.indexOf('red') === 0) ? 'yellow' : 'red';
        jQuery(foo[1]).after("<b>Hello</b>");
    }
    foo[2].onmouseover = function () {
        this.style.backgroundColor = (this.style.backgroundColor.indexOf('green') === 0) ? 'yellow' : 'green';
        jQuery(foo[3]).toggle("slow");
        jQuery('b').remove();
    }
};
window.onload = init;

What does this mean?

Upvotes: 0

Views: 25727

Answers (2)

Guffa
Guffa

Reputation: 700302

It means that you are setting the init function to handle the onload event of the document. The init function will be called when all the content in the page has loaded.

As you are using jQuery, you should use the jQuery events instead. The DOM events can only have one handler (unless you write code to chain the handlers), but the jQuery events can have multiple handlers:

$(document).load(init);

If you have more than one script in the page that uses the onload event, one will replace the other. Even if you use jQuery events, a script that hooks up the DOM event will take over the jQuery event handler, like in this question. Using the jQuery event in all scripts solves that.

Upvotes: 6

defau1t
defau1t

Reputation: 10619

This means that on the load of window the function init will be executed.

Upvotes: 2

Related Questions