Saturday, September 27, 2008

Prevent accidental window closing: alert onbeforeUnLoad

Today, I'm going to show you how to stop your visitor to close window of your site, using JavaScript.

It's useful when they have unfinished processes, or unsaved data, in which they whether accidentally or deliberately clicked on the close button of your page.

It's also useful for your marketing strategy, like one-time offer, final discounts, and so on.

Simple. First, use this following function. Then I'll show you with 3 situations for example.

<script>
var askFirst = false;
function preventerOn() {
askFirst = true;
}

function preventerOff() {
askFirst = false;
}
window.onbeforeunload = sureUnload;
function sureUnload() {
if (askFirst)
return "Are you sure you want to exit this page?";
}
</script>


Situation 1, if you want to prevent window closing from the beginning, you may want to use the body tag, like this:

<body onload="return preventerOn();">


Situation 2, if you want to prevent window closing when your visitor enter something in a form, use it like this:

<input type="text" name="input1" onchange="return preventerOn();">


Situation 3, if you want to prevent window closing before reached an amount of time (i.e: 20 seconds), you may add this one to the script above:

function setTimer() {
preventerOn();
setTimeout("clear();",20000); // 1000 is for 1 second, so 20000 is for 20 seconds
}
function clear() {
preventerOff();
}


You may need to change in the body tag, from this:

<body onload="return preventerOn();">


to this:

<body onload="return setTimer();">


That's all.

If you have any questions regarding this, please feel free and don't hesitate to ask me through the comment form.

Thank you.

3 comments:

Bobby said...

Hey, this is a useful post and a great idea for certain situations. I am adding this post to Stumbleupon and it should bring it a surge of visitors! Is there a way to make a page un-closeable?

lmtips said...

I would specificly say do not use this. It will do nothing but annoy users.

The last 3 years in webdesign and researching how to make internet users happy has shown me this.

ImamKhalid said...

Bobby, un-closeable page is a bad idea. I wouldn't recommend it.

Imtips, you'll always have the choice, whether to put it or not. But sometimes in some web applications, we really need this function to be working! :)