I am trying to implement similar functionality as mentioned in jQuery Key Events with a Search Box
I would like to arrow up and down the search results and select the result on enter key or mouse click.
Find my code at: http://jsfiddle.net/CyQ2w/
3 issues:
I am able to arrow up and down, but when I arrow down after the last item, the selection on item disappears. I am trying to disable browsing after last item i.e., keep the last item selected. Same thing happens for first item when we up arrow on it.
When I mouse over the item list and mouse out, the selection hover is removed and now arrow up and down do not work.
Also, on enter key doesn't seem to set the textarea with the item selected. I am trying to capture "id" of selected li.
Any help will be hig开发者_如何学Gohly appreciated.
For your first problem you can add a check like the following -
...
else if (code === 40) { //Down arrow
if($("li.hovered").index()==$("li").length-1) return;
...
else if (code === 38) { //Up arrow
if($("li.hovered").index()==0) return;
...
This means when you are in the first item index 0
pressing the up arrow will do nothing.
BTW, 38 is not down arrow its up arrow. Don't make other confused. I hope you can do the Down check yourself.
You can solve the second problem like the following -
$("#userlist_container li").hover(function () {
$('li.hovered').removeClass('hovered');
$(this).addClass("hovered");
}, function () {
// $(this).removeClass("hovered");
});
And your third problem is little hard to explain without the whole code so check my updated code at http://jsfiddle.net/CyQ2w/7/
You should block events with e.preventDefault();
精彩评论