views:

64

answers:

1

Hi,

Is there a way to prevent the default action from occurring when the user presses backspace on a browser? I don't need to prevent the user from leaving, just from having the default backspace action. I need the backspace to do something different (it's a game).

I tried without success:

window.addEventListener('keydown', function(e) {
    if (e.keyCode === Game.Key.BACK_SPACE)
    {
        e.preventDefault();
        e.stopPropagation();
        return false;
    }
}, false);

If I put an alert inside the if, the alert will be shown for backspace key press. So, the keyCode is correct.

Edit: This has to work in Opera 10.6, Firefox 4, Chrome 6, IE 9 and Safari 5.

+2  A: 

You don't need return false or e.stopPropagation(); neither will make any difference in a listener attached with addEventListener. Your code won't work in Opera, which only allows you to suppress the default browser behaviour in the keypress event, or IE <= 8, which doesn't support addEventListener. The following should work in all browsers, so long as you don't already have keydown and keypress event handlers on the document.

EDIT: It also now filters out events that originated from an <input> or <textarea> element:

function suppressBackspace(evt) {
    evt = evt || window.event;
    var target = evt.target || evt.srcElement;

    if (evt.keyCode == 8 && !/input|textarea/i.test(target.nodeName)) {
        return false;
    }
}

document.onkeydown = suppressBackspace;
document.onkeypress = suppressBackspace;
Tim Down
While this works, it prevents inputs from working. It shouldn't prevent backspace on input elements.
rFactor
That would be true of your solution too if it worked. I'll edit my answer.
Tim Down
..... and done.
Tim Down
Do you think it's possible to do it the other way -- prevent the user from leaving the page rather than trying to stop all backspace actions?
rFactor
No, you can't stop the user from leaving the page. The browser prevents this, and rightly: it's up to the user if they want to leave the page. There is an `unload` event (and `beforeunload` in many browsers) that fires as the page is about to close or go somewhere else, but you can't suppress that event.
Tim Down