Detecting the Page Leave event in JavaScript

March 26, 2012 in JavaScript

You may need to detect if the user is leaving your web page for displaying a warning message to the user mentioning that he may not leave the page and the form is containing data filled by him. To be able to detect this event in JavaScript, you need to deal with the "onbeforeunload" event. The following example explains the idea.

In this example, there is a simple form that contains an input text. When the user enters something in the input text, a warning message appears.

<HTML>
<HEAD>
	<TITLE>Welcome to the test Page</TITLE>
	<SCRIPT type="text/javascript">
		window.onbeforeunload = function(event) {
			
			if (hasData()) {
				return "You entered information in the page. Are you sure you want to leave now?"; // Very important
			}
		}
		
		function hasData() {
			var someThing = document.getElementById("someThing");
			
			if (someThing.value != "") {
				return true;
			}		
			
			return false;
		}
	</SCRIPT>
	
</HEAD>
<BODY>
	<H1>Welcome to the test page</H1>
	
	<FORM>
		<LABEL for="someThing">Enter something here:</LABEL>
		<INPUT type="text" id="someThing"/>
	</FORM>
</BODY>
</HTML>

The "onbeforeunload" event is called when the user tries to leave the page. As shown in the code, to display the interruption message "You entered information in the page. Are you sure you want to leave now?", you have to specify the interruption message in the return of the event. The interruption message is displayed as shown in the figure below.
IE Preview

This code works with me on IE, Firefox, and Safari. I wish that this tip can be useful for you.

Leave a reply

Your email address will not be published. Required fields are marked *

259,379 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by sweetCaptcha