jquery - Iterate array on current position -
i've got array letters. right , left key want navigate left , right, on enter key, want current position (or letter) activated , , down keys change letter @ current position. when pressing enter again want leave activated state , able move left , right again. left , right navigation works , down arrows changes letters @ same time. guess need use $(this)
in way. i'm sorry if code looks messy, can't pieces this. happy if point me in right direction!
// $( document ).ready() var letters = ['','a','b','c','d','e']; var letterindex = 0; $('a:first').focus(); $(document).keydown(function(e) { e.preventdefault(); var keycode = e.which; arrow = {up: 38, down: 40, right: 39, left: 37, enter: 13}; switch(e.which) { case arrow.up: letterindex = letterindex + 1; $(this).find('a').html(letters[letterindex]); break; case arrow.down: letterindex = letterindex - 1; $(this).find('a').html(letters[letterindex]); break; case arrow.right: $('a:focus').closest('li').next().find('a').focus(); break; case arrow.left: $('a:focus').closest('li').prev().find('a').focus(); break; case arrow.enter: $(this).find('a').focus().toggleclass('highlight'); break; } }); });
html
<ul> <li><a href="">a</a></li> <li><a href="">b</a></li> <li><a href="">c</a></li> <li><a href="">d</a></li> </ul>
this want.
improvements:
1. letterindex
should not global vairable each link element maintains own state.
2. bind event each link element , use $(this)
rather searching event owner using find()
.
var letters = ['','a','b','c','d','e']; $('a:first').focus(); $("a").on('keydown', function(e){ e.preventdefault(); var keycode = e.which; arrow = {up: 38, down: 40, right: 39, left: 37, enter: 13}; //each link has own state variable needs local letterindex = letters.indexof($(this).html()); //loop index max min if(letterindex == letters.length) letterindex = -1; switch(e.which) { case arrow.up: letterindex = letterindex + 1; $(this).html(letters[letterindex]); break; case arrow.down: letterindex = letterindex - 1; $(this).html(letters[letterindex]); break; case arrow.right: $(this).closest('li').next().find('a').focus(); break; case arrow.left: $(this).closest('li').prev().find('a').focus(); break; case arrow.enter: $(this).focus().toggleclass('highlight'); break; } });
Comments
Post a Comment