Ghozt
Ghozt

Reputation: 267

why does body onload work but window.onload or document.onload NOT work

So I want to hide a div, so I have my code

function hide(){hide div code}

document.onload = hide();

Does not work.

window.onload = hide();

Does not work.

However if I go to the HTML document and write

<body onload="hide()"> 

This works.

Now I understand that I should not have javascript in the html document, but how do I actually make the javascript WAIT until the entire page has loaded and then execute some code. I am certain that the code is running before the page has loaded, and I just cant work out why.

Do you have any ideas on how I can make this work?

Upvotes: 0

Views: 2518

Answers (3)

bastos.sergio
bastos.sergio

Reputation: 6764

Also, you can try calling your code like this:

window.onload = function () { hide(); }

Upvotes: 1

Ghozt
Ghozt

Reputation: 267

Yeah I fixed it, it was another JS element causing trouble with my function!

Upvotes: 0

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262939

To make this work, you have to pass the function itself instead of calling it and passing the value it returns.

It means you have to write:

window.onload = hide;  // Without parentheses.

In passing, note that onload is only supported by window, not document.

Upvotes: 2

Related Questions