Is there a way to prevent the default action from occurring when the user presses backspace in 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.
This has to work in Opera 10.6, Firefox 4, Chrome 6, Internet Explorer 9 and Safari 5.
Use the onkeydown event and preventDefault() method to Disable Backspace and Delete key in JavaScript. Backspace char code is 8 and deletes key char code is 46.
You can-not actually disable the browser back button. However, you can do magic using your logic to prevent the user from navigating back which will create an impression like it is disabled.
Select Settings from the list. Scroll down to the Privacy and Security section, and select the Site settings from the menu. Choose the Pop-ups and redirects option within Site settings. Toggle the button to turn OFF and block the pop-ups and redirection.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With