简体   繁体   中英

How to exclude down arrow key from event-listener

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');
                    }
                }
            });

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM