Introduction:
Some time while development we face a situation to check whether user want to close page or not. So in that case we have to confirm this on closing the page or on going backward or forward.
In this article I will discuss how to confirm before leaving
page. We use Javascript function to confirm this. We use window.onbeforeunload event to achieve this.
<script type="text/javascript">
var
hook = true;
window.onbeforeunload = function () {
if
(hook) {
return
"Did you save your changes?"
}
}
function
unhook() {
hook = false;
}
</script>
|
Demo Application with code:
Full Code for Sample webpage:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"
runat="server">
<title></title>
<script type="text/javascript">
var
hook = true;
window.onbeforeunload = function () {
if
(hook) {
return
"Did you save your stuff?"
}
}
function
unhook() {
hook = false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<center>
<fieldset style="width:300px"><legend><strong>Confirm Before Leaving page</strong></legend>
<div><br /><br />
Ask User If he wants to close Page or
not.
<br /><br />
</div></fieldset></center>
</form>
</body>
</html>
|
Use the above code and check result.
Note:
You can ask if you have doubt in article or other article by posting in comment
area.