onbeforeunload
onbeforeunload Event
The onbeforeunload
event is fired when a user attempts to leave a webpage, providing an opportunity to display a confirmation prompt. This is commonly used to prevent accidental loss of data, particularly in forms or when editing content.
Syntax
In HTML
<element onbeforeunload="myScript">
In JS
object.onbeforeunload = function(){myScript};
addEventListener()
function is used. In JavaScript, the
object.addEventListener("beforeunload", myScript);
Example
<!DOCTYPE html>
<html>
<body onbeforeunload="return myFunction()">
<h1>HTML DOM Events</h1>
<h2>The beforeunload Event</h2>
<p>This example assigns an "onbeforeunload" event to a body element.</p>
<p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>
<a href="https://institute.qarpeo.com">Click here to go to Qarpeo.com</a>
<script>
function myFunction() {
return "Write something clever here...";
}
</script>
</body>
</html>
Value
<script>
- Specifies the script to execute when the event is triggered.
Conclusion
The onbeforeunload
event helps alert users before they navigate away, reducing the risk of losing unsaved work. However, its behavior may differ between browsers, so thorough testing is recommended for compatibility.
onbeforeprint
The onbeforeunload event activates a function before the page is unloaded, giving you the opportunity to warn users about unsaved changes or show a confirmation dialog when they try to navigate away or reload the page.
oncopy
The oncopy event attribute in HTML triggers a function when the user copies content from an element.