HTML onunload Event Attribute

If this site has been useful, we’d love your support! Running this site takes time and resources, and every small contribution helps us keep creating valuable content. Consider buying us a coffee to keep things going strong!

Description

The onunload HTML event attribute fires once a page has unloaded (or the browser window has been closed). It is most often used to perform cleanup tasks, such as saving form data, clearing cookies, or logging out of a user account.

The onunload event is triggered when the user navigates away from the page (by clicking on a link, submitting a form, closing the browser window, etc.). It is also triggered when the page is reloaded.

To use the onunload event attribute, simply add it to the element on which you want to listen for the event. The value of the attribute should be a JavaScript function that will be executed when the event fires.

Here is an example of how to use the onunload event attribute:

<body onunload="myUnloadFunction()">
  </body>

The myUnloadFunction() function will be executed when the user navigates away from the page.

Here is an example of a simple myUnloadFunction() function:

function myUnloadFunction() {
  // Save form data
  // Clear cookies
  // Log out user account
}

It is important to note that the onunload event may not be triggered in all cases. For example, if the user navigates to another page using the browser's back or forward buttons, the onunload event will not be triggered.

Overall, the onunload event attribute is a useful tool for performing cleanup tasks when a page is unloaded. However, it is important to be aware of the limitations of the event.

Syntax

<element onunload="script">

Values

  • scriptThe name of the script to use when the event has been triggered.

Example

<!DOCTYPE html> 
<html>
<head>
<title>onunload event</title>
</head>
<body onunload="LeaveUser()">
<script>
function LeaveUser() {
alert("EXAMPLE: See you again!");
}
</script>
Leave this page to see the event trigger.
<br><br>
Note: Due to different browser settings, this event may not always work as expected.
</body>
</html>

Browser Support

The following table will show you the current browser support for the HTML onunload Event Attribute.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 14th October 2023