Event Listener Examples

Keyboard Events

You can use the addEventListener() method to listen for keyboard events at the document level.

document.addEventListener('keydown', function(event) { });
document.addEventListener('keyup', function(event) { });
document.addEventListener('keypress', function(event) { });

Use the following code to check out the keydown event object.

document.addEventListener('keydown', (e) => {
    console.log(e);
})

Keydown switch statement example

e.keyCode is deprecated

document.addEventListener('keydown', (e) => {
    switch (e.key) {
        case 'ArrowUp':
            console.log(`${e.key} key pressed`);
            break;
        case 'ArrowDown':
            console.log(`${e.key} key pressed`);
            break;
        case 'ArrowLeft':
            console.log(`${e.key} key pressed`);
            break;
        case 'ArrowRight':
            console.log(`${e.key} key pressed`);
            break;
    }
})

When done, don't forget to remove the event listener with the removeEventListener() method.

Additional Resources

Key Codes