HTML event attribute onload








The onload attribute event is triggered when an element has been loaded.

onload is most often used within the <body> element to execute a script when a web page has completely loaded all content, including images, script files, CSS files, etc.

We can also use onload attribute event with iframe.

What's new in HTML5

None.

Syntax

<element onload="script or Javascript function name">

Supported Tags

<body>, 
<frame>, 
<frameset>, 
<iframe>, 
<img>, 
<input type="image">, 
<link>, 
<script> 
<style>




Browser compatibility

onload Yes Yes Yes Yes Yes

Example

The following code handles the onload event on body element.

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {<!--from w ww .  j  a v a2s.  c o m-->
    alert("Page is loaded");
    
    if (navigator.cookieEnabled == true) {
        alert("Cookies are enabled.");
    } else {
        alert("Cookies are not enabled.");
    }    
}
</script>
</head>

<body onload="myFunction()">
   <h1>Hello World!</h1>
   
</body>

</html>

Click to view the demo





Example 2

The following code handles the onload event for an image element.

<!DOCTYPE html>
<html>
<body>
<!--  w ww.j av  a 2 s .  c om-->
<img src="http://java2s.com/style/demo/border.png" onload="loadImage()" width="100" height="100">

<script>
function loadImage() {
    alert("Image is loaded");
}
</script>

</body>
</html>

Click to view the demo