Tuesday, June 23, 2009

Warning before navigate away from a page (JavaScript)

In some cases, if you are in between any work of editing or typing a content, and you wont let the visitor to navigate away from the page without particular condition, say the document is not saved yet, you can block the navigation (even the closing of the browser window) with Javascript.

Here is the javascript code for that:


window.onbeforeunload = function (evt)
{
var message = ‘Are you sure you want to leave?’;
if (typeof evt == ‘undefined’)
{
evt = window.event;
}
if (evt)
{
evt.returnValue = message;
}
return message;
}


Just paste this code anywhere in your html page. The condition settings , warning messages are up to you. In the above code, the warning will be displayed when ever a navigation happen (Even closing of browser window happen).

No comments:

Post a Comment