select li element with arrow keys 28up and down 29 using javascript

Solutions on MaxInterview for select li element with arrow keys 28up and down 29 using javascript by the best coders in the world

showing results for - "select li element with arrow keys 28up and down 29 using javascript"
Pedro
25 Apr 2018
1var li = $('#list > li');
2var liSelected;
3$(window).on('keydown', function(e){
4var selected;
5if(e.which === 40){
6	if(liSelected){
7		liSelected.removeClass('background');
8		next = liSelected.next();
9		if(next.length > 0){
10			liSelected = next.addClass('background');
11			selected = next.text();
12
13		}else{
14			liSelected = li.eq(0).addClass('background');
15			selected = li.eq(0).text();
16		}
17	}else{
18		liSelected = li.eq(0).addClass('background');
19			selected = li.eq(0).text();
20	}
21}else if(e.which === 38){
22	if(liSelected){
23		liSelected.removeClass('background');
24		next = liSelected.prev();
25		if(next.length > 0){
26			liSelected = next.addClass('background');
27			selected = next.text();
28
29		}else{
30
31			liSelected = li.last().addClass('background');
32			selected = li.last().text()
33		}
34	}else{
35
36		liSelected = li.last().addClass('background');
37		selected = li.last().text()
38	}
39}
40console.log(selected)
41});
42
43/*HTML FILE CODE
44
45<!DOCTYPE html>
46<html>
47<head>
48	<meta charset="utf-8">
49	<meta http-equiv="X-UA-Compatible" content="IE=edge">
50	<title></title>
51    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
52	<link rel="stylesheet" href="">
53	<style>
54		.background{
55			background: hsla(0, 100%, 0%, 0.4);
56		}
57	</style>
58</head>
59<body>
60	<input type="text" class="form-control" id="searchProduct" placeholder="Search..." />
61	<ul id="list">
62    <li id="match1" class="itemList">1</li>
63    <li id="match2" class="itemList">2</li>
64    <li id="match3" class="itemList">3</li>
65	</ul>
66</body>
67</html>
68
69
70
71
72
73*/