javascriptdom-eventsevent-listenerdom3

Disable backspace with DOM Level 3 Listeners


I am making a page in which a user must be able to type. The default function of backspace is to go back a page, however I need to prevent this and assign my own function to it.

The problem is actually preventing backspace. I can capture it however I can not prevent it. I am using Level 3 event listeners. event.preventDefault() did not work for me and neither did return false.

I have tried this also:

function onunload(e) {
    if (e.keyCode == 37) return false;
    return true;
}

and

<body onunload="return false;">

However the first basically does

return confirm("false");

and the second does nothing?


Solution

  • Preventing backspace key altogether might not be a good idea, assume you make a typo and want to fix it in a text box! So you need to disable backspace only if someone is not typing in a text input!

    This might work in all major browsers:

    document.onkeydown = function (e) {
        e = e || window.event;
        if (e.keyCode == 8) {                                           // Disable Backspace
            var el = document.activeElement;
            if (!((el.nodeName == "INPUT" && (el.type == "text" || el.type == "password")) || el.nodeName == "TEXTAREA")) {
                e.preventDefault();
                e.stopPropagation();
                return false;
            }
        }
    };
    

    DOM3 event model spec comes with backward compatibility so I don't think this might be an issue, however this is the DOM3 modified version of the above code:

    function KeyDownHandler(e) {
        if (e.keyCode == 8) {                                           // Disable Backspace
            var el = document.activeElement;
            if (!((el.nodeName == "INPUT" && (el.type == "text" || el.type == "password")) || el.nodeName == "TEXTAREA")) {
                e.preventDefault();
                e.stopPropagation();
            }
        }
    };
    
    if (document.attachEvent) document.attachEvent("onkeydown", KeyDownHandler);
    else document.addEventListener("keydown", KeyDownHandler);
    

    A DOM3 event registration like the one above might be a great pain, John Resig has a good implementation on this, you could however use a standard cross browser library like JQuery which works fine in all major browsers!