lovesh
lovesh

Reputation: 5411

onload event on document.body behaving strange

I am using firefox 4.0 and when i use load event on the body element it behaves strange. i have tried some things and some work and some dont. the first is like this

<html>
<head>
<script type="text/javascript">
var load = function(){
alert("body loaded");      //alert not displayed
};
document.body.addEventListener("load",load,false);
</script>
</head>
<body >
</body>
</html>

now this doesnt work now i tried this

     html>
    <head>
    <script type="text/javascript">
    var load = function(){
    alert("body loaded");      //alert displayed
    };
    </script>
    </head>
    <body onload="load()">
    </body>
    </html>

this works now i tried this

<html>
<head>
<script type="text/javascript">
var load = function(){
alert("body loaded");       //alert not displayed
};
document.body.onload=load;
</script>
</head>
<body >
</body>
</html>

this doesnt work. Whats wrong?

as response to Doug D i tried this

<html>
<head>
</head>
<body>
<script type="text/javascript">
var load = function(){
alert("body loaded");       //alert not displayed
};
document.body.onload=load;
</script>
</body>
</html>

this doesnt work either neither does this work

<html>
<head>
</head>
<body>
</body>
<script type="text/javascript">
var load = function(){
alert("body loaded");       //alert not displayed
};
document.body.onload=load;
</script>
</html>

in the last attempt the body has finished loadingand in the second last attempt body is being loaded. but this does not work still

Upvotes: 2

Views: 826

Answers (1)

Doug Domeny
Doug Domeny

Reputation: 4470

The body can't be accessed in the head until it has been loaded. Your second technique of using the onload attribute is correct. Alternately, I would recommend using jQuery with

$(document).ready(function()
{
    alert("body loaded");
});

It is cross-browser compatible. Without jQuery you would need to deal with DOM event differences between IE and others.

Upvotes: 1

Related Questions