Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

select li element with arrow keys (up and down) using javascript

var li = $('#list > li');
var liSelected;
$(window).on('keydown', function(e){
var selected;
if(e.which === 40){
	if(liSelected){
		liSelected.removeClass('background');
		next = liSelected.next();
		if(next.length > 0){
			liSelected = next.addClass('background');
			selected = next.text();

		}else{
			liSelected = li.eq(0).addClass('background');
			selected = li.eq(0).text();
		}
	}else{
		liSelected = li.eq(0).addClass('background');
			selected = li.eq(0).text();
	}
}else if(e.which === 38){
	if(liSelected){
		liSelected.removeClass('background');
		next = liSelected.prev();
		if(next.length > 0){
			liSelected = next.addClass('background');
			selected = next.text();

		}else{

			liSelected = li.last().addClass('background');
			selected = li.last().text()
		}
	}else{

		liSelected = li.last().addClass('background');
		selected = li.last().text()
	}
}
console.log(selected)
});

/*HTML FILE CODE

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
	<link rel="stylesheet" href="">
	<style>
		.background{
			background: hsla(0, 100%, 0%, 0.4);
		}
	</style>
</head>
<body>
	<input type="text" class="form-control" id="searchProduct" placeholder="Search..." />
	<ul id="list">
    <li id="match1" class="itemList">1</li>
    <li id="match2" class="itemList">2</li>
    <li id="match3" class="itemList">3</li>
	</ul>
</body>
</html>





*/
 
PREVIOUS NEXT
Tagged: #select #li #element #arrow #keys #javascript
ADD COMMENT
Topic
Name
4+1 =