You don’t have to create a new event listener to listen to every shortcut. You only need one event listener.
Let’s say you want to listen to the h key to open a help menu. You also want to use the Escape key to quit a feature. Here’s what you do:
document.addEventListener('keydown', event => {
const { key } = event
if (key === 'h') {
console.log('Open help menu')
}
if (key === 'Escape') {
console.log('Quit feature!')
}
})
That said, it might be better to use multiple event listeners if code gets complicated.
Ignoring cases
Does it matter if users type in a lowercase letter or an uppercase letter? It shouldn’t matter most of the time. If it doesn’t matter, you want to ignore cases.
To ignore cases, you can convert the key to lowercase before checking.
document.addEventListener('keydown', event => {
const key = event.key.toLowercase()
if (key === 'h') {
console.log('Open help menu')
}
})
This also makes checking for keys like Escape easier, because you don’t have to remember to capitalize the E.