Forum Moderators: open

Message Too Old, No Replies

Wierd DOM Behavior

         

prezet

1:38 pm on Aug 10, 2006 (gmt 0)

10+ Year Member



Hi

I'm having some wierd behavior with the DOM and the window.onload event. Even when I strip my original code back to a basic example it's still not working.

I was under the impression the window.onload event was only fired once everything on the page (including the DOM had loaded). However what I'm experiencing here is that a function being called by the window.onload event is being triggered before the DOM fully loads, hence it doesn't work....

Heres the code:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
#test {
width: 100%;
height: 50px;
background-color: #0033CC;
}
p {
cursor: pointer;
}
</style>
<script language="javascript" type="text/javascript">
function changeColor() {
alert("Starting Function...");
target = document.getElementById("test");
target.style.display = "none";
}
window.onload = changeColor();
</script>
</head>
<body>
<div id="test"></div>
<p onClick="changeColor();">If the Blue Bar is still visible, click here to rerun the function</p>
</body>
</html>

and you can see it in action here:
www.caistorhall.com/newsite/test2.htm

Anyone got any ideas whats happening....?

Cheers
Lee

afmbr

12:30 am on Aug 11, 2006 (gmt 0)

10+ Year Member



window.onload = changeColor();

You're not getting a reference for your function. You're actually calling it.

Try the following:

window.onload = changeColor;

prezet

10:48 am on Aug 11, 2006 (gmt 0)

10+ Year Member



Thanks.

Could someone explain the difference?

supermoi

3:36 pm on Aug 13, 2006 (gmt 0)

10+ Year Member



changeColor() means that you want to assign the value returned by the function to the onload event. So when the assignment is made, the function is called to get the returned value.