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};
addEventListener()
function is used. In JavaScript, the
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.
onmessage
The onmessage event is triggered when a message is received via an event source. The event object for this event includes the following properties.
onpageshow
The onpageshow event in HTML is triggered when a webpage is displayed, allowing developers to perform actions or restore the page's state as the user returns.