43

Notice while on Google's homepage, with no focus on any element, pressing BACKSPACE will put the focus into the search toolbar instead of navigating back.

How can I accomplish this?

I keep running into this problem with users in my app. They don't have focus on any element and hit BACKSPACE which throws them out of the app.

FastTrack
  • 8,810
  • 14
  • 57
  • 78
  • The answers to this question are not good enough. They are too complex, might not catch all cases of accidental navigation, and might disable the normal "backspace" function in unusual input fields. Ideally, the companies that make the browsers should disable this bone-headed key binding by default. Until that might happen, I suggest to simply confirm navigation if any text has been entered into form fields. The second answer here looks good: http://stackoverflow.com/questions/5102602/confirm-to-leave-the-page-when-editing-a-form-with-jquery – Sam Watkins May 21 '15 at 06:00
  • 1
    There is a similar question here, which also has inadequate answers: http://stackoverflow.com/questions/1495219/how-can-i-prevent-the-backspace-key-from-navigating-back – Sam Watkins May 21 '15 at 06:01

9 Answers9

66

I would bind an event handler to keydown and prevent the default action of that event if we're dealing with the backspace key outside of a textarea or input:

$(document).on("keydown", function (e) {
    if (e.which === 8 && !$(e.target).is("input, textarea")) {
        e.preventDefault();
    }
});
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • why you want to add `&& !$(e.target).is("input, textarea")` line extra ,@FastTrack always try to make your code short –  Jun 20 '12 at 02:58
  • 2
    Somebody: I chose this answer because it will prevent BACKSPACE all the time unless the focus is on an `input` or `textarea`. – FastTrack Jun 20 '12 at 02:59
  • @muhammadkashif: What problem are you having? I just tried in FF 17.0.1 and have no issues... – Andrew Whitaker Dec 27 '12 at 15:58
  • In my case , I have a page opening inside another page as a popup. When I hit the backspace button, it closing the popup and redirecting me to the previous page. This happens only in FireFox. I handled it by replacing keydown to keypress. But still on a page where all controls are disables Firefox does not catch the keypress event. Can you help me in this? – muhammad kashif Dec 28 '12 at 04:58
  • I just saw answer by J.Money. Trying it. – muhammad kashif Dec 28 '12 at 05:00
  • everything work fine , except that if focus is on a submit button, backspace fires ! how to prevent this ? – armen Jun 05 '13 at 09:06
  • also, eg in Firefox we also can navigate using Alt + Left / Right keys. hot to prevent this ? – armen Jun 05 '13 at 09:19
  • Let's not forget contentEditable divs... :) see http://stackoverflow.com/questions/1495219/how-can-i-prevent-the-backspace-key-from-navigating-back – Neek Feb 25 '14 at 10:32
  • To be compatible with IE: if (e.preventDefault) e.preventDefault(); else e.returnValue = false; – ravinsp Jan 23 '15 at 05:40
  • This isn't working when clicking on `checkbox` and entering `backspace`. The page navigates to back. How to solve this problem? – Ankit Feb 17 '16 at 20:17
24

I really like Andrew Whitaker's answer. It will, however, still navigate back when focused on a readonly, radio, or checkbox input field and will not allow backspace on contentEditable elements so I have added a slight modification. Credit goes to Andrew Whitaker.

$(document).on("keydown", function (e) {
    if (e.which === 8 && !$(e.target).is("input:not([readonly]):not([type=radio]):not([type=checkbox]), textarea, [contentEditable], [contentEditable=true]")) {
        e.preventDefault();
    }
});

At the moment it seems to be necessary to have every variation [contentEditable] that is in the HTML since [contentEditable] != [contentEditable=true].

None
  • 5,491
  • 1
  • 40
  • 51
11

The way Google does this is kinda cool. When you press backspace, they focus the text field, preventing the users to navigate back!

You can try the same:

<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<input id="target" type="text" />

<script type="text/javascript">
$(document).keydown(function(e) { if (e.keyCode == 8) $('#target').focus(); });
</script>

demo : http://jsfiddle.net/epinapala/TxG5p/

Eswar Rajesh Pinapala
  • 4,841
  • 4
  • 32
  • 40
  • Thanks for the answer! I chose the one above only because it will prevent BACKSPACE all the time unless the focus is on an `input` or `textarea`. But your answer is also very helpful. – FastTrack Jun 20 '12 at 02:57
  • 1
    anytime! I just wanted to explain how google does this(i think its the same).. :) – Eswar Rajesh Pinapala Jun 20 '12 at 03:00
  • 2
    Although this works with 1 input field and Google homepage has only one input field, it cannot be used on pages with more than 1 input because deleting text will cause the field to switch focus to #target. That is why Andrew Whitaker's answer is the better solution. – None Dec 07 '12 at 03:03
  • 1
    @J.Money - I agree, But please understand that I was answering OP's question. If one had to make assumptions to answer a question, there would be thousands of answers possible :) – Eswar Rajesh Pinapala Dec 07 '12 at 05:42
  • @Eswar Yes, but it is good practice to write code that is reusable. While your code could be used on a very specific page, Andrew's could be used on the set of pages your answer addresses and many others. There are thousands of possible assumptions and possible answers, but Andrew's 5 lines of code addresses thousands of possible situations. I am not saying that you didn't answer the question. I am simply stating that your answer, while a solution, is not the best solution because of its many drawbacks. Hopefully people will understand these drawbacks and choose the answer best suited for them – None Dec 08 '12 at 00:15
  • @J.Money: that is the reason why I was one of those who +1 his answer. I don't say that my and is the best , i explained you why i gave my ans. my intention is to answer the op question- solve what he was looking for(what google does) . so I don't think there is a need for us to argue .. – Eswar Rajesh Pinapala Dec 09 '12 at 01:47
2

Here is a simple solution tested on IE, Chrome and Firefox.

$(document).on("keydown", function (event) {
// Chrome & Firefox || Internet Explorer
if (document.activeElement === document.body || document.activeElement === document.body.parentElement) {
    // SPACE (32) o BACKSPACE (8)
    if (event.keyCode === 32 || event.keyCode === 8) {
        event.preventDefault();
    }
}});
PiotrWolkowski
  • 8,408
  • 6
  • 48
  • 68
spuentep
  • 101
  • 6
1

This is old, but these answers will still allow you to backspace and navigate when focused on a radio button. You will want to filter the input type as well. Credit to all answers above for this:

$(document).on("keydown", function (e) {
    if (e.which === 8 && !$(e.target).is("input[type='text']:not([readonly]), textarea")) {
        e.preventDefault();
    }
});
KingOfHypocrites
  • 9,316
  • 9
  • 47
  • 69
  • Good catch but it may be better to specify `input:not([type=radio])` specifically since `input[type=text]` will make it so you can't delete within password or email input fields. I did some more testing and updated my answer. – None Jan 02 '15 at 13:25
1

To stop from navigating simply this code works!

$(document).on("keydown", function (event) {        
   if (event.keyCode === 8) {
      event.preventDefault();
    }
  });

But that will even also happen for input fields type text/textarea. So to restrict it for those fields, you may use

$(document).on("keydown", function (event) {
  if (event.which === 8 && !$(event.target).is("input, textarea")) {
   event.preventDefault();
  }
});

In my case where I had a text field for calendar and whenever I'd click on that calendar, Select date and press backspace it'd navigate back to previous page. To prevent it for that field only I simply used

$('#myField').on("keydown", function (event) {
  if (event.keyCode === 8 || event.which === 8) { 
   event.preventDefault(); 
  } 
});

I thought to mention for some to help ;-)

0

I've tryed many of the code snippets on the internet without satisfyind result. The new browser versions of IE (IE11) and Crome broke my former solution, but here is what works for me with IE11 + Crome + Firefox. The code prevents backspace and the user doesn't lose anything of what he has keyed in in a text field:

window.addEventListener('keydown', function (e) {
    if (e.keyIdentifier === 'U+0008' || e.keyIdentifier === 'Backspace' || e.keyCode === '8' || document.activeElement !== 'text') {
        if (e.target === document.body) {
            e.preventDefault();
        }
    }
}, true);
FastTrack
  • 8,810
  • 14
  • 57
  • 78
LarsOlsen
  • 1
  • 1
0

For Internet Explorer , this worked for me :

window.addEventListener('keydown', function (e) {

    if (e.keyCode === 8) {
       if (e.target === document.body) {
           e.preventDefault();
       }
    }
}, true);
Ale
  • 944
  • 3
  • 14
  • 34
Gurpreet Singh
  • 1,641
  • 3
  • 17
  • 29
0

Handled readonly text boxes also

$(document).keydown(function (e) {
        var activeInput = $(document.activeElement).is("input[type=text]:not([readonly]):focus, textarea:focus");
        if (e.keyCode === 8 && !activeInput) {
            return false;
        };
    });
Vijai
  • 2,369
  • 3
  • 25
  • 32