I would like to have live search box acting like google , I have implement jquery ajax to backend for getting results , but I want to enable when user press key down i would like to add a class to the ajax return suggestion just like google, when user press up suggestion hightlight will go up a place when user press enter it will go to the href. below are my ajax return html codes:
<ul id="suggestion" style="list-style-type: none;">
<li><a class="suggestion-link" href="http://eled.test/post/sunt-iure-nihil-deleniti-rerum"> Sunt Iure Nihil Deleniti Rerum.</a>
</li>
<li><a class="suggestion-link" href="http://eled.test/post/porro-et-numquam-nihil-nesciunt-nesciunt"> Porro Et Numquam Nihil Nesciunt Nesciunt.</a>
</li>
<li><a class="suggestion-link" href="http://eled.test/post/my-new-post-yeah"> My New Post Yeah !!</a> </li>
<li><a class="suggestion-link" href="http://eled.test/post/rerum-voluptatem-fuga-excepturi-provident-et-distinctio"> Rerum Voluptatem Fuga Excepturi Provident Et...</a>
</li>
</ul>
below is my search form
<form method="GET" action="{{route('home.search')}}" class="search-form" id="search-form" >
<div class="form-group">
<input type="text" name="keyword" id="search-input" placeholder="What are you looking for?" autocomplete="off">
<button type="submit" class="submit"><i class="fas fa-search"></i></button>
</div>
<ul id="suggestion" style="display: none;list-style-type: none; "></ul>
</form>
below is my ajax
$(document).ready(function() {
//sidebar search function ajax
$("#search-input").keyup(function() {
var keyword = $('#search-input').val();
var url = "{{route('home.ajax_search')}}";
if (keyword == "") {
$("#suggestion").html("");
$('#suggestion').hide();
}else {
$.ajax({
type: "GET",
url: url ,
data: {
keyword: keyword
},
success: function(data) {
$("#suggestion").html(data).show();
//console.log(data);
$('#search-input').on("keydown", function (e) {
var listItems = $('.suggestion-link');
switch(e.which) {
case 38:
console.log('up');
break;
case 40:
listItems.addClass('selected');
console.log('down');
break;
default: return;
}
});
}
});
}
});
});
inside the ajax i can get console log working when try key down and up. 38 / 40 but I cant add the selected class the li element I follow this Add keydown (keyboard arrow up/down) support for AJAX Live Search PHP the problem is I could not apply class active to the return element so user wont know the key down/up is working thanks