HTML onpagehide Event Attribute

Description

The onpagehide HTML event attribute specifies the script that will be run when the user navigates away from a page. It can be used to perform any tasks that need to be done before the page is unloaded, such as saving data or clearing cookies.

The onpagehide event is triggered when the user clicks on a link, refreshes the page, submits a form, closes the browser window, or otherwise navigates to a different page. It is sometimes used instead of the onunload event, as the onunload event causes the page to not be cached.

To use the onpagehide event, simply add the onpagehide attribute to the <body> element of your HTML document and specify the name of the JavaScript function that you want to run when the event is triggered. For example:

<body onpagehide="myOnpagehideFunction()">

The myOnpagehideFunction() function will be run whenever the user navigates away from the page.

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

function myOnpagehideFunction() {
  // Save any data that needs to be saved before the page is unloaded.
  // Clear any cookies that need to be cleared.
}

You can use the onpagehide event to perform any tasks that you need to do before the user navigates away from your page. This can be useful for ensuring that your page is in a clean state before the user leaves.

Syntax

<element onpagehide="script">

Values

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

Example

<!DOCTYPE HTML>
<html>

<body onpagehide="onPageHide()">
<p>
Note: Due to various browser settings, this event may not always work as expected..<p/>
<script>
function onPageHide() {
alert ("EXAMPLE: Thanks, please come back again.");
}
</script>
</body>

</html>

Browser Support

The following table will show you the current browser support for the HTML onpagehide 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