Search code examples
javascriptjqueryscrollkeydownonkeydown

jQuery: How to detect arrow key press only on certain element


I am new to jQuery and am trying to find a way to detect an arrow key press (only up and down). When searching for this online I came across this post from here.

This looks very good but I want to detect the arrow key press only when the user is on an element with a certain class (i.e. the element has focus) that is added dynamically to a page.

Specifically I would like to highlight the corresponding list item when pressing the up or down arrow key on a list with focus.

Is there a way this can be achieved and work cross-browser ?

It looks like this already happens automatically but in my case it doesn't work properly and always skips list items which is why I thought I can define it separately.

Example element:

<ul class="myClass" id="someID">
   <li><a href="#">Value1</a></li>
   <li><a href="#">Value2</a></li>
   <li><a href="#">Value3</a></li>
</ul>

Many thanks in advance for any help, Mike


Solution

  • Instead of

    $(document).keydown(function(e) {
    

    in your javascript code have

    $(<selector>).keydown(function(e) {
    

    where <selector> points to the element you want to track.

    UPDATE

    Better - since you mention dynamically added elements, use delegation structure of event binding:

    $(document).on("keydown", ".<yourClassName>", function(e) {