Skip to content

Instantly share code, notes, and snippets.

@thiagoaag
Last active October 21, 2015 17:49
Show Gist options
  • Save thiagoaag/ad676417db1223e956b2 to your computer and use it in GitHub Desktop.
Save thiagoaag/ad676417db1223e956b2 to your computer and use it in GitHub Desktop.
Navigating in the list by arrows keyboard
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$( window ).load(function() {
window.index = -1;
$("#search").keyup(function(e){
switch(e.keyCode){
case 40:
navigate(1);
break;
case 38:
navigate(-1);
break;
case 13:
$("#search").val( $(list[index]).text() );
break;
}
});
var list = $(".lista li");
var navigate = function(diff) {
index += diff;
console.log('index: ' + index + ' | ' + 'diff: ' + diff );
if (index >= list.length){
index = 0;
}
if (index < 0){
index = list.length - 1;
}
var cssClass = "display_box_hover";
console.log('index: ' + index);
list.removeClass(cssClass).eq(index).addClass(cssClass);
}
});
</script>
<style type="text/css">
.display_box_hover, li:hover
{
background:#3b5998;
color:#FFFFFF;
}
</style>
</head>
<body>
<input type="text" id="search" name="search_fld"/>
<div id="display" class="lista">
<ul>
<li >black</li>
<li >blue</li>
<li >brown</li>
<li >green</li>
<li >pink</li>
<li >red</li>
<li >violet</li>
<li >white</li>
<li >yellow</li>
</ul>
<ul >
<li >black</li>
<li >blue</li>
<li >brown</li>
<li >green</li>
<li >pink</li>
<li >red</li>
<li >violet</li>
<li >white</li>
<li >yellow</li>
</ul>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment