Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery arrow key navigation

I have these textfield and dropdown menu for a Facebook like autosuggestion:

<input type="text" id="search" name="search_fld"/>

<div id="display">
<div class="display_box">Luca</div>
<div class="display_box">David</div>
<div class="display_box">Mark</div>
<div class="display_box">...</div>
</div>

My CSS:

.display_box:hover
{
  background:#3b5998;
  color:#FFFFFF;
}

How can I achieve to pass the 'hover' state with down arrow key from my input "search_fld" to the first 'display_box' and so on for all the "display" divs?

Here is a link the jsfiddle code.

like image 843
luca Avatar asked Apr 04 '11 11:04

luca


People also ask

How do I navigate with arrow keys?

Arrow keys - Using the arrow keys on the keyboard, move the cursor up, down, left, or right in the document. Ctrl and Arrow keys - Holding down the Ctrl key while pressing the left or right arrow keys moves the cursor one word at a time. Using this shortcut is much faster than only using the arrow keys.


1 Answers

You can't emulate the hover state perfectly.. there's no escape from adding "real" class with the same style:

.display_box_hover, .display_box:hover
{
  background:#3b5998;
  color:#FFFFFF;
}

Now this code will "naviage" the elements:

window.displayBoxIndex = -1;

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

});

var Navigate = function(diff) {
    displayBoxIndex += diff;
    var oBoxCollection = $(".display_box");
    if (displayBoxIndex >= oBoxCollection.length)
         displayBoxIndex = 0;
    if (displayBoxIndex < 0)
         displayBoxIndex = oBoxCollection.length - 1;
    var cssClass = "display_box_hover";
    oBoxCollection.removeClass(cssClass).eq(displayBoxIndex).addClass(cssClass);
}

This will "remember" the index of the last "selected" element and switch to next or previous element, using the eq() function and adding the class from above to that selected element.

Updated jsFiddle.

like image 151
Shadow Wizard Hates Omicron Avatar answered Nov 05 '22 00:11

Shadow Wizard Hates Omicron