How can I use a 'keydown' event listener on a div?

rabbitwerks picture rabbitwerks · Jul 10, 2018 · Viewed 8.7k times · Source

I am trying to capture keydown events where specific keys correspond to specific audio clips to be played. I've been searching but I am stumped. It seems that the keydown event is only available in the window/document object. Is this correct? Ive seen some talk of jQuery plugins, although i would like to stay away from jQuery. Vanilla JS is ideal.

I have 2 DIVS that I want to listen for keydown events on at the same time. Based on which keys are pressed, the function plays the corresponding audio clip.

Thank you!

Answer

iota picture iota · Jul 10, 2018

Give the div a tabindex, so it will be focusable. In your case, a tabindex of -1 would be best as it would allow the element to be focused but remain inaccessible by the tab key.

The tabindex global attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation (usually with the Tab key, hence the name).

A negative value (usually tabindex="-1") means that the element should be focusable, but should not be reachable via sequential keyboard navigation. It's mostly useful to create accessible widgets with JavaScript.

You can then add a keydown event listener to the element and check for the keyCode of the event.

document.getElementById("someId").addEventListener("keydown", function(event){
    //do something on keydown
    if(event.keyCode==13){
     //enter key was pressed
    }
    if (event.keyCode >= 65 && event.keyCode <= 90){
       //input was a-z
    }
});