The HTML onunload attribute is an event handler that triggers the script to execute when a page is completely unloaded.
Definition and Usage
➔ This is often used for final cleanup or logging purposes before the user leaves the site.
➔ This event occurs when the user does one of the following:
- Navigates away from the page,
- clicks on a link,
- Closes the browser window,
- Submits a form,
- or reloads the page.
Syntax
//In HTML
<body onunload="myFunction()">
<!-- page content -->
</body>
//In javascript
window.onunload=function() {myFunction();};
//OR
window.addEventListener("unload", myFunction());
//OR
window.addEventListener("unload", (event) => {
myFunction();
});
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML unload Attribute Example</title>
<meta charset="utf-8" />
</head>
<body>
<h2>HTML unload Attribute Example</h2>
<p>onunload occurs when the user refresh the page, click on a link, submit a form, close the browser.</p>
<script>
function myFunction(event) {
alert("onunload event is triggered.");
}
window.addEventListener("unload", myFunction());
</script>
</body>
</html>