SQL PHP HTML ASP JavaScript articles and free scripts to download
JavaScript Window Object

window.onload for executing as soon as page loads

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.

The other way to achieve the same result is by using onload inside body tag of the page. You can read this article on how to keep the onload event handler to set the focus on input tag once the page loads.

Let us start some simple example of uses of window.onload function where we will prompt a message box once the page loads.

demo of window onload event

Here is the script
<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 ?

Difference between window.onload function and body tag onload. We can't keep any code to access the property set or any other related objects of the elements present in body of the page by using window.onload function. Say we want to select the text present inside a text box as soon as the page loads. This is not possible by using window.onload event but this is possible by using body onload command. The code below will generate error message.
<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 >
<form name=form1 method=post action=''>
<input type=text name=t1 value=plus2net id="t2">
</form>

</body>
</html>

Be the first to post comment on this article :


Google+

Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked




HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us

©2000-2014 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer