0

My intention is to prevent the Backspace key from navigating back to the previous URL in the history stack of browsers.

index.html

<html>
<head>
    <script type="text/javascript" src="app.js"></script>
</head>
<body>
    <input type="text">    
</body>
</html>

app.js

window.addEventListener('keydown', function(e) {
    if(e.key === 'Backspace') {
        e.preventDefault();
    }
}, false);

I used preventDefault() on key events with useCapture disabled. It did prevent the Backspace key from its default action. However, now I can't use Backspace key anywhere else (Eg: to delete text from the input box).

Why is it so? Aren't input boxes supposed to behave normally since window will get the event only at the very end (the event is registered in bubbling mode) and won't the preventDefault be called only then?

Manu Soman
  • 153
  • 11
  • The js code will work everywhere in your page. Writing an eventListener for the backspace is described [here](https://stackoverflow.com/q/1495219/6826260) using jquery – G. Siganos Sep 23 '19 at 10:31
  • @G.Siganos I understand. But why the default action of the input box is prevented? That is what I need to know. – Manu Soman Sep 23 '19 at 11:55
  • You are binding the pressing of any key, everywhere in your page with this code. If you want the backspace to work only in inputs, you have to exclude them use this (its a bad idea and rather messy): `window.addEventListener('keydown', function(e) { if(e.key === 'Backspace') { var myinput = document.getElementById('my-input'); var isInputFocued = document.activeElement == myinput; if(!isInputFocued ){ e.preventDefault(); } } }, false);` and the html `` – G. Siganos Sep 23 '19 at 12:49

0 Answers0