Harshvardhan Solanki Harshvardhan Solanki - 3 months ago 7
HTML Question

How to disable Spacebar and Tab keypress on a Web Page using Jquery?

I have a "popup" div which when displayed I want to disable any

keypress
or
keydown
event on the page.

I tried this code below:

$(document).on('keypress keydown',function (e) {
var key = e.which;
if(key == 32 && $(".popup").is(":visible")){
// console.log($(".popup").is(":visible"));
// alert("keypresses yr "+(key == 32 && $(".popup").is(":visible")));
e.preventDefault();
return false;
}
});


Here in
if
condition I check if key pressed is
spacebar (32)
and the
popup
box is visible than only disable
keypress
.

Did not work!

I am using jquery version
1.11.1
.

Answer

Try switching your code to the following:

$(document).on('keypress keydown',function (e) {
    return $(".popup").is(":visible") && e.which !== 9 && e.which !== 32;
});

The code above will return every key pressed except tab and space, if the popup is visible.

Working Snippet:

$(document).on('keypress keydown', function(e) {
  /* I changed it to ':focus' to demonstrate how it works inside the input */
  return $("#txt").is(":focus") && e.which !== 9 && e.which !== 32;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input id="txt" type="text" />