Harshvardhan Solanki Harshvardhan Solanki - 1 year ago 75
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

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")));
return false;

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

Did not work!

I am using jquery version

Answer Source

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" />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download