onunload
The onunload event in HTML is triggered when a user leaves the page, enabling developers to run code right before the page is unloaded.
onunload event
The onunload
event handler activates a script when the user leaves the page or navigates away. It is commonly used for tasks like cleaning up resources or saving data before the page is closed.
Syntax
In HTML
index.html
<element onchange="myScript">
In JS
script.js
object.onunload = function(){myScript};
addEventListener()
function is used. In JavaScript, the
script.js
object.addEventListener("unload", myScript);
Example
::event-onunload
::
index.html
<!DOCTYPE html>
<html>
<body onunload="myFunction()">
<h1>Welcome to my Home Page</h1>
<p>Close this window or press F5 to reload the page.</p>
<p><strong>Note:</strong> Due to different browser settings, this event may not always work as expected.</p>
<script>
function myFunction() {
alert("Thank you for visiting Qarpeo!");
}
</script>
</body>
</html>
This logs a message to the console when the user navigates away from or closes the page.
Values
Conclusion
The onunload
event in HTML is triggered when a user leaves or navigates away from a page, allowing developers to execute code before the page is unloaded. This is commonly used for tasks like cleanup or saving user data. The event can be applied in HTML attributes, JavaScript functions, or with addEventListener()
.