What is the JavaScript code/event(s) that is used by sites like stackoverflow and Gmail to test for the user exiting the page once they have begun editing and try to navigate away?
"Are you sure you want to navigate away from this page?"
vb. 1 to plan, direct, or plot the path or position of (a ship, an aircraft, etc.) 2 tr to travel over, through, or on (water, air, or land) in a boat, aircraft, etc. 3 Informal to direct (oneself, one's way, etc.) carefully or safely.
The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.
The event used is called onbeforeunload
.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<input id="foo"></input>
<script type="text/javascript">
function unloadMessage() {
return "Are you sure you want to leave?";
}
function setConfirmUnload(enabled) {
window.onbeforeunload = enabled ? unloadMessage : null;
}
$(document).ready(function() {
$("#foo").keypress(function() {
setConfirmUnload(true);
});
});
</script>
</body>
</html>
onbeforeunload event. Mozilla provides useful example code. you just want to have a function that:
The string will be used as your custom message.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With