Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 675
rabbitwerks Avatar asked Jul 10 '18 14:07

rabbitwerks


2 Answers

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
    }
});
like image 78
Unmitigated Avatar answered Oct 06 '22 22:10

Unmitigated


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

like image 44
Andrei Nemes Avatar answered Oct 06 '22 22:10

Andrei Nemes