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

You can allow an element to receive focus by giving it a tab index.

<div tabindex="-1"></div>

As long as it's in focus key events should be captured on it.

If you want the element to be focusable using the Tab key, give it an index greater than -1.

Simple example


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
    }
});