HTML onunload Event Attribute


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()">

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.


<element onunload="script">


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


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

Browser Support

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

Edge Chrome Firefox Opera Safari
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview

Last updated by CSSPortal on: 14th October 2023