Javascript - How to focus on links in a list using keyboard arrow keys

I can change focus when links are not wrapped in other elements.

It works:

HTML

<a id="first" href="#" class='move'>Link</a>
<a href="#" class='move'>Link</a>
<a href="#" class='move'>Link</a>

JS (with jQuery)

$(document).keydown(
    function(e)
    {    
        // Down key
        if (e.keyCode == 40) {      
            $(".move:focus").next().focus();       
        }

        // Up key
        if (e.keyCode == 38) {      
            $(".move:focus").prev().focus();       
        }
    }
);

Demo script

But how can I achieve the same when the links are inside the list, for example? Like this

<ul>
    <li>
        <a id="first" href="#" class='move'>Link</a>
    </li>
    <li>
        <a href="#" class='move'>Link</a>
    </li>
    <li>
        <a href="#" class='move'>Link</a>
    </li>
</ul> 
+3
source share
3 answers

You can use .closest () to find the parent, then use .next () to get the next li, and then use .find () to get the next .move

    if (e.keyCode == 40) {      
        $(".move:focus").closest('li').next().find('a.move').focus();   
    }

    // Up key
    if (e.keyCode == 38) {      
        $(".move:focus").closest('li').prev().find('a.move').focus();   
    }

Demo

+6
source
if (e.keyCode == 40) {      
  $(".move:focus").parent().next().find('a').focus();   
}
if (e.keyCode == 38) {      
  $(".move:focus").parent().prev().find('a').focus();   
}
+1
source

, , , - :

var $li = $('li'),

$move = $(".move").click(function () {
    this.focus();
});

$(document).keydown(function(e) {
    if (e.keyCode == 40 || e.keyCode == 38) {
        var inc = e.keyCode == 40 ? 1 : -1,
            move = $move.filter(":focus").parent('li').index() + inc;
        $li.eq(move % $li.length).find('.move').focus();
    }
});

$move.filter(':first').focus();

: http://jsfiddle.net/WWQPR/5/

+1

All Articles