Window.onload function we can use to perform some task as soon as the page finishes loading. This JavaScript function is used in different condition like displaying a print page or directing focus ( keeping the crusher blinking ) to user input field as soon as the page is loaded.
<html>
<head>
<title>(Type a title for your page here)</title>
<script type="text/javascript">
function my_code(){
alert(" Alert inside my_code function");
}
window.onload=my_code();
</script>
</head>
<body >
</body>
</html>
We can also achieve the same result by using onload event of body tag. Then what is the difference ?
<body onLoad="my_code()";>
Example : To keep the userid textbox on focus & selected ( time of loading of page )
<body onLoad="document.f1.userid.focus()";>
<html>
<head>
<title>(Type a title for your page here)</title>
<script type="text/javascript">
function my_code(){
alert(" Alert inside my_code function");
var text_val = document.getElementById("t2");
text_val.select();
}
window.onload=my_code();
</script>
</head>
<body >
<form name=form1 method=post action=''>
<input type=text name=t1 value=plus2net id="t2">
</form>
</body>
</html>
The above code won't work and you can see the error message in your JavaScript console. To make this code work we have to change the window.onload command.
<html>
<head>
<title>(Type a title for your page here)</title>
<script type="text/javascript">
function my_code(){
alert(" Alert inside my_code function");
var text_val = document.getElementById("t2");
text_val.select();
}
//window.onload=my_code();
</script>
</head>
<body onload=my_code()>
<form name=form1 method=post action=''>
<input type=text name=t1 value=plus2net id="t2">
</form>
</body>
</html>
<html>
<head>
<title>(Type a title for your page here)</title>
<script type="text/javascript">
function my_code(){
alert(" Alert inside my_code function");
console.log("First onload function");
secondOnload();
}
function secondOnload() {
console.log("Second onload function");
}
window.onload=my_code();
</script>
</head>
<body >
<form name=form1 method=post action=''>
<input type=text name=t1 value=plus2net id="t2">
</form>
</body>
</html>
window.addEventListener("load", function() {
console.log("This is triggered by addEventListener");
});
Explanation:window.onload event in JavaScript?window.onload event?window.onload event occurs?window.onload after the page has finished loading?window.onload event handler on a single page?window.onload event differ from the DOMContentLoaded event?window.onload event before accessing or manipulating the DOM?window.onload event?window.onload event has already occurred?window.onload event?
| Amar | 27-11-2014 |
| Both codes above in comparison are same. | |
| Azim | 24-06-2015 |
| Thank You so much | |
| diya | 01-02-2016 |
| I did not understand the difference, when onload is in body and head, if it is head noticed that i should be giving "window.onload=my_code();" but for the body i should be giving window.onload=my_code; | |