Search code examples
javascriptjquerynavigationtaggingarrow-keys

How do I enable arrow navigation on keyboard for a list of Div using jQuery


I am following a tutorial [here][1] to make a Facebook like friend tagging system. But the tutorial lacks the "arrow navigating" capability like Facebook. I would like to figure out how to achieve this.

Basically, when I input text on the contenteditable area, it will generate divs of suggested friends like the following:

<div class="display_box">    
   <img src="user_img/John.jpg">
   <a href="#" class="addname" title="John">John</a><br>
   <span>India</span>
</div>
<div class="display_box">    
   <img src="user_img/Peter.jpg">
   <a href="#" class="addname" title="Peter">Peter</a><br>
   <span>USA</span>
</div>
<div class="display_box">    
   <img src="user_img/Mary.jpg>
   <a href="#" class="addname" title="Mary">Mary</a><br>
   <span>UK</span>
</div>

They are all divs with the class name display_box. I can click on the box and select them by:

$('div').on("click",".display_box",function(e) {
    // do the stuffs
}); 

I would like my users to be able to use the keyboard, using key up or key down to navigate between the selections, and use the enter key to trigger the selection. Any ideas how can I make this happen? Many thanks!


Solution

  • You need to bind keyboard events keyup/keydown and then change the css accordingly to give a feel of move up or move down :

    use keyup if you want a single move even on a key press no matter the key is long pressed.

    use keydown if you want to move in a cycle fashion as long as user holds the key.

    $("#search").keyup(function(e) 
    {
            if (e.keyCode == 40) 
            {  
                Navigate(1);
            }
            if(e.keyCode==38)
            {
                Navigate(-1);
            }
    
    });
    

    Check complete code @fiddle: http://jsfiddle.net/MKZSE/77/