onbeforeunload

The onbeforeunload event attribute triggers a function before the page is unloaded, allowing you to warn users about unsaved changes.

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

index.html
<element onbeforeunload="myScript">

In JS

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

In JavaScript, the addEventListener() function is used.

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

Example

::event-bfunload ::
index.html
<!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.