Reputation: 9868
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.
Upvotes: 2
Views: 2293
Reputation: 9868
// 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
Upvotes: 7