Get keyboard events from an HTML element

Posted on June 15, 2020

Get keyboard events from an HTML element

TIL how to listen for keyboard events from a specific HTML element.

It's about adding this attribute:

<div tabindex="0"></div>

then, attach the listener:

let el = document.querySelector('div')
el.addEventListener('keydown', e => {
  console.log(e)
})

this way the above function will be called when the user last click has been done on that element.

The nice part is that it works with many elements out of the box, proof here.