-1

By default, when we press a space bar key over document it scrolls down. To prevent the default behaviour, we could do the following :

$(document).keypress(function(event) {
   event.preventDefault();
});

But we cannot do the above, when we have certain input fields, for it will not allow us to type into the text fields.

How could I prevent the default action of space bar, without infringing the rights of others!

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
  • Your code is also likely to break other things (such as using the tab key to navigate around the page) so you should be more discriminatory about when you prevent the default action (i.e. check it is actually the space bar that was pressed). – Quentin Mar 17 '15 at 11:54

2 Answers2

2

You can either:

  1. Check event.target to see if it is an input element and not prevent default if it is or
  2. Bind event handlers to the input elements which stop propagation

I'd just not break normal scrolling features in the first place though.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

I recently had the same problem. Apparently here is how I solved it:

$(document).keypress(function(event) {
    if (
        ['input', 'textarea', 'select', 'button']
        .indexOf(document.activeElement.tagName.toLowerCase()) == -1
    ) {
        // Current focused element is NOT an input. Let's prevent scroll!
        event.preventDefault();
        // Now we can do various stuff.
    } else {
        // User is typing something into a focused input.
        // Do NOT do anything here.
    }
}
Andrew Dunai
  • 3,061
  • 19
  • 27