HTML body onload
Created By: chatGPT
In HTML, the
onload
event is triggered when the entire page is fully loaded, including all dependent resources such as stylesheets and images. This is particularly useful for running JavaScript functions immediately after all elements are available in the DOM. The body
tag can have an onload
attribute to specify a function to be executed when the page is finished loading.<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Onload Example</title>
<script>
function pageLoaded() {
alert('Page is fully loaded!');
}
</script>
</head>
<body onload="pageLoaded()">
<h1>Welcome to My Page</h1>
<p>This page demonstrates the onload event.</p>
</body>
</html>
This example uses the
onload
attribute to call the JavaScript function pageLoaded()
when the page is loaded. The function simply shows an alert message. You can replace the alert with any other code you need to execute after the page load.// Another example of using onload
function initialize() {
console.log('Page is properly loaded');
// Additional initialization code here
}
If you want to do more than just show an alert, you could also manipulate the DOM. For instance, changing the content of an element or styling it can all be done within the onload function.
<script>
function changeContent() {
document.getElementById('message').innerText = 'Content has changed!';
}
</script>
<body onload="changeContent()">
<h1>Welcome to My Page</h1>
<p id="message">This will change on load.</p>
</body>