onpagehide

The onpagehide event is triggered when the user is leaving a webpage. This can happen through various actions, such as clicking a link or closing the browser tab.

onpagehide event

The onpagehide event triggers a script when the user leaves the current page. It is commonly used to save user data or manage page transitions.

Syntax

In HTML

index.html
<element onpagehide="myScript">

In JS

script.js
object.onpagehide = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("pagehide", myScript);

Example

::event-onpagehide ::
index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page Hide Event Example</title>
</head>
<body>
<h1>Page Hide Event Example</h1>
<p>Open the console and navigate away or close the tab to trigger the event.</p>

<script>
  function handlePageHide() {
    alert("Page is being hidden or unloaded.");
  }
  window.addEventListener("pagehide", handlePageHide);
</script>

</body>
</html>

Values

Conclusion

The onpagehide event is useful for executing actions when a user leaves or hides a webpage. It can help in saving data or handling page transitions. This event enhances the user experience by ensuring that important tasks are completed before the page is unloaded.