Prevent BACKSPACE from navigating back with jQuery (Like Google's Homepage)

前端 未结 9 957
陌清茗
陌清茗 2020-11-30 22:48

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

相关标签:
9条回答
  • 2020-11-30 23:45

    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();
        }
    });
    
    0 讨论(0)
  • 2020-11-30 23:47

    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();
        }
    }});
    
    0 讨论(0)
  • 2020-11-30 23:49

    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 讨论(0)
提交回复
热议问题