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

喜欢而已 提交于 2019-12-24 02:59:15

问题


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!


回答1:


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/



来源:https://stackoverflow.com/questions/28147266/how-do-i-enable-arrow-navigation-on-keyboard-for-a-list-of-div-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!