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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With