Built From Developers For Developers
» Kuikie.com » Snippets » JavaScript » Other » JQuery. Prevent Browser Redirection on User Clicking Backspace
  Categories
  JavaScript
    Ajax
    IFrame
    Integers
    Other
    Strings
 

JQuery. Prevent Browser Redirection on User Clicking Backspace

The user browsers do redirect the user a page back when the backspace button is pressed. However in many cases this behaviour is undesirable as it may break the user experience. For instance when a user fills in a form and presses the backspace to delete a letter in a text field.

The following JQuery snippet solves the problem.

// Prevent the backspace key from navigating back.
$(document).unbind('keydown').bind('keydown', function (event) {
    var doPrevent = false;
    if (event.keyCode === 8) {
        var d = event.srcElement || event.target;
        if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD')) 
            || d.tagName.toUpperCase() === 'TEXTAREA') {
            doPrevent = d.readOnly || d.disabled;
        } else {
            doPrevent = true;
        }
    }

    if (doPrevent) {
        event.preventDefault();
    }
});
 
©2012 Sinevia Ltd Terms of Use         Privacy Policy Valid XHTML 1.0 Transitional