HTML onload Event Attribute
Description
The onload
HTML event attribute fires when an object has been loaded. It is most often used within the <body>
element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.). However, it can be used on other elements as well, such as images and links.
The onload
attribute can be used for a variety of purposes, such as:
- To display a loading animation while the page is loading
- To initialize JavaScript variables and objects
- To check the user's browser type and version and load the appropriate content
- To redirect the user to a different page
- To display a pop-up message
Here is an example of how to use the onload
attribute on the <body>
element:
<body onload="myFunction()">
...
</body>
The myFunction()
function will be executed once the page has completely loaded.
Here is an example of how to use the onload
attribute on an image element:
<img src="my-image.png" onload="myFunction()">
The myFunction()
function will be executed once the image has been loaded.
Syntax
<element onload="script">
Values
- scriptThe name of the script to use when the event has been triggered.
Example
<!DOCTYPE html>
<html>
<head>
<title>onload event</title>
</head>
<body>
<img src="2.png" alt="CSS" onload="LoadInfo()">
<p id="test"> </p>
<script>
function LoadInfo() {
document.getElementById("test").innerHTML = "Image loaded successfully!";
}
</script>
</body>
</html>
Browser Support
The following table will show you the current browser support for the HTML onload
Event Attribute.
Desktop | |||||
Yes | Yes | Yes | Yes | Yes |
Tablets / Mobile | |||||
Yes | Yes | Yes | Yes | Yes | Yes |
Last updated by CSSPortal on: 14th October 2023