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

前端 未结 9 970
陌清茗
陌清茗 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: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 ;-)

提交回复
热议问题