'How to tell if an element accepts keyboard input?

I'm working on keyboard shortcuts for a web application and need to check if a keypress should trigger the shortcut or if it is just the user typing and should therefore not trigger the shortcut.

For example, a common pattern is to use the / or s keys to open the global search bar. Obviously this should not open the search bar if the user is typing into another input.

The ideal logic would go something like this: On keypress, check the currently focused element. If the element accepts keyboard input (can be typed into), then do nothing. If the element does not accept keyboard input, run the shortcut.

Note that checking for focusability is not enough because links and buttons are focusable, but do not accept keyboard input (in the way I mean here).

Here's what I have so far:

function acceptsKeyboardInput(element) {
    return (
        element.tagName === "INPUT" ||
        element.tagName === "TEXTAREA" ||
        element.isContentEditable
    );
}

Does this approach catch every case or is there a better way to tell if an HTML element accepts keyboard input?



Solution 1:[1]

Will all shortcuts be more than one key? If so you can listen for input and prevent a shortcut from running with a boolean value.

var is_input = false
window.addEventListener('keydown', function (e) {
    console.log(is_input)
    is_input = false
})
window.addEventListener('input', function (e) {
    is_input = e.constructor.name == 'InputEvent'
})

Expected output for /s while able to type would be true or false (depending on the previous is_input value) at / keypress then true at s keypress and all keys following.

Expected output for /s while not able to type would be true or false (depending on the previous is_input value) at / keypress then false at s keypress and all keys following

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Spencer May