Skip to content

Instantly share code, notes, and snippets.

@getsetbro
Created May 1, 2014 03:28
Show Gist options
  • Save getsetbro/11443940 to your computer and use it in GitHub Desktop.
Save getsetbro/11443940 to your computer and use it in GitHub Desktop.
#app *{
box-sizing: border-box;
}
#list{
height:202px;
overflow:auto;
list-style:none;
margin:0;
padding:0;
border:1px solid #999;
}
li{
padding:10px 10px 0 10px;
height:40px;
}
.selected{
background-color:#999;
color:#fff;
outline: 0 none;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>keydown list</title>
<meta name="description" content="nav a list with arrow keys" />
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
</head>
<body id="app">
<ul id="list">
<li tabindex="0">test 1</li>
<li tabindex="1">test 2</li>
<li tabindex="2">test 3</li>
<li tabindex="3">test 4</li>
<li tabindex="4">test 5</li>
<li tabindex="5">test 6</li>
<li tabindex="6">test 7</li>
<li tabindex="10">test 11</li>
<li tabindex="11">test 12</li>
<li tabindex="12">test 13</li>
<li tabindex="13">test 14</li>
<li tabindex="14">test 15</li>
<li tabindex="15">test 16</li>
<li tabindex="16">test 17</li>
<li tabindex="20">test 21</li>
<li tabindex="21">test 22</li>
<li tabindex="22">test 23</li>
<li tabindex="23">test 24</li>
<li tabindex="24">test 25</li>
<li tabindex="25">test 26</li>
<li tabindex="26">test 27</li>
</ul>
<div id="info"></div>
</body>
</html>
$("li").bind({
keydown: function(e) {
var key = e.keyCode;
var target = $(this);
switch(key) {
case 38: // arrow up
e.preventDefault(); //prevent arrow scroll
target.prev().focus();
break;
case 40: // arrow down
e.preventDefault(); //prevent arrow scroll
target.next().focus();
break;
}
},
focusin: function(e) {
$('#list').find('.selected').removeClass("selected");
$(this).addClass("selected");
$('#info').html(e.target.tabIndex + 1);
},
focusout: function(e) {
//$(e.currentTarget).removeClass("selected");
},
click:function(e){
this.focusin();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment