Preventing backspace from navigating back in all the browsers

July 16, 2012 in JavaScript, Web 2.0

One of the requirements which you may face is preventing the backspace key from navigating back in the browser. This requirement can be achieved by listening on the keyboard keys in the browser and acting when the backspace key is pressed under the condition that the mouse cursor is NOT inside an input or a text area elements. Actually, you have to take care of the IE broken event model when you are implementing this feature. for example, the event.stopPropagation() method is not working in IE, adding to this, you have to get the keycode from the window.event not from the passed event object to the event handler.

I wrote the following code which works on all the common browsers (IE, Safari, Chrome, and Firefox) perfectly, and I wish it can be useful for you:

document.onkeydown = function (event) {
	
	if (!event) { /* This will happen in IE */
		event = window.event;
	}
		
	var keyCode = event.keyCode;
	
	if (keyCode == 8 &&
		((event.target || event.srcElement).tagName != "TEXTAREA") && 
		((event.target || event.srcElement).tagName != "INPUT")) { 
		
		if (navigator.userAgent.toLowerCase().indexOf("msie") == -1) {
			event.stopPropagation();
		} else {
			alert("prevented");
			event.returnValue = false;
		}
		
		return false;
	}
};	

Using this code inside a <script> tag of the HTML <body> element can do this job for you.

Leave a reply

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

332,663 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 sweet Captcha