Reputation:
I am developing a dictionary which has autocomplete when I start typing it shows words as list starting with that letter. (Like vocabulary.com)
searchInput.addEventListener('keyup',function(){
let search = $('#search').val()
$.ajax({
type: 'GET',
url: '/home/autocomplete/' + search
dataType: "json",
success: function (response) {
let word = response.words
suggestionsPanel.innerHTML = '';
$.each(word, function (idx, w) {
$('.suggestions').append(`<li name = ${w}>${w}</li>`)
// $('.suggestions li:first').addClass('selected')
})};
Now i want to add down arrow key to go move through list. I added another key down event listener buy it keeps executing first event listener function. How to make it both work?
var li = $('.suggestions > li');
var liSelected;
$(window).keydown(function(e) {
if(e.which === 40) {
if(liSelected) {
liSelected.removeClass('selected');
next = liSelected.next();
if(next.length > 0) {
liSelected = next.addClass('selected');
} else {
liSelected = li.eq(0).addClass('selected');
}
} else {
liSelected = li.eq(0).addClass('selected');
}
} else if(e.which === 38) {
if(liSelected) {
liSelected.removeClass('selected');
next = liSelected.prev();
if(next.length > 0) {
liSelected = next.addClass('selected');
} else {
liSelected = li.last().addClass('selected');
}
} else {
liSelected = li.last().addClass('selected');
}
}
});
Upvotes: 0
Views: 310
Reputation: 34556
The keyup
event emits a keyCode
property, which you can use to identify the down arrow key.
If found, you can then exit the callback on that basis.
The down arrow key has a key code of 40.
searchInput.addEventListener('keyup', function(evt) {
if (evt.keyCode == 40) return;
//otherwise continue...
Upvotes: 1