1

I want to use JavaScript to detect when the spacebar is pressed. I want to exclude all events in which any input is focused. Is this possible with pure JS?

Note: The main point of this question is excluding all events in which an input is focused.

quemeful
  • 9,542
  • 4
  • 60
  • 69
  • Possible duplicate of [respond to key press javascript](http://stackoverflow.com/questions/7600892/respond-to-key-press-javascript) – iwein May 17 '16 at 19:04
  • The main point of this question is excluding all events in which an input is focused. – quemeful May 17 '16 at 19:40
  • that other question is just a key press detection – quemeful May 17 '16 at 19:40
  • 1
    So, more like http://stackoverflow.com/questions/1621346/excluding-form-fields-from-keypress-handler-assigned-to-body? – Paul Roub May 17 '16 at 19:50
  • yes. thank you @Paul Roub. I hate when people are so quick to mark as duplicate without reading all the details. – quemeful May 17 '16 at 20:01

1 Answers1

6
// capture keyboard input
document.onkeypress = function (e) {

    // check for spacebar press
    if (e.keyCode == 32) {

        // check if an input is currently in focus
        if (document.activeElement.nodeName.toLowerCase() != "input") {

            // prevent default spacebar event (scrolling to bottom)
            e.preventDefault();

            // do stuff you want ...
        }
    }
};

some other element to watch for spacebar focus:

  • textarea
  • button
quemeful
  • 9,542
  • 4
  • 60
  • 69
  • 2
    I know the OP didn't mention it, but probably a good idea to exclude textarea too. – dmeglio May 17 '16 at 18:53
  • 2
    ... and ` – Stephen P May 17 '16 at 18:55