Source Code: (back to article)
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Window Events Demo</title>
<style>
#message {
padding: 20px;
margin: 20px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<p>Watch how the message updates based on window events. Initially, it changes upon loading. If you attempt to exit or click the mock exit link below, a prompt will appear asking if you want to leave the page. Cancelling the action will update the message.</p>
<div id="message">Wait for it...</div>
<!-- Mock link for simulating page leave -->
<a href="#" onclick="simulatePageLeave(); return false;">Mock Page Leave</a>
<script>
window.onload = function() {
document.getElementById('message').innerHTML = '<strong>Window loaded successfully!</strong>';
};

// Function to simulate page leave
function simulatePageLeave() {
// Show dialog asking if the user really wants to leave
var confirmLeave = confirm('Are you sure you want to simulate leaving the page?');
if (confirmLeave) {
// If confirmed, update message as if leaving
document.getElementById('message').innerHTML = '<strong>Leaving the page...</strong>';
} else {
// If cancelled, update message accordingly
document.getElementById('message').innerHTML = '<strong>Decided to stay on the page!</strong>';
}
}

window.onbeforeunload = function() {