Send focus to dynamic li with jQuery

cbloss793 picture cbloss793 · Jan 29, 2016 · Viewed 14.3k times · Source

I was wondering if you can send focus to a dynamic li. Here's what I'm trying to do:

I've got a search box that has a keyup function bound to it where it searches for people's names. The results appear in a div right below the search box with a ul of results. I was hoping to make it where if someone hits the down arrow button that the focus gets switched to the first element of the ul. Kind of like how a drop down works. Here's the code (I didn't put in all the CSS so it doesn't look as pretty as it should--just FYI)

I have tried $('#search_results').find('li:first').focus(), $('#search_results').find('li:first').trigger('focus'). Nothing works. Anyone have any feedback?

Answer

ameenulla0007 picture ameenulla0007 · Jan 29, 2016

you need to just play with CSS & some jquery here. here is your fiddle. https://jsfiddle.net/7h0pavzb/ need to add a class to show that it is selected.

your jquery

$(document).ready(function(){
  $('#search_name').keyup(function(e) {
        if(e.which == 40){
            if($("#search_results li.active").length!=0) {
                var storeTarget = $('#search_results').find("li.active").next();
                $("#search_results li.active").removeClass("active");
                storeTarget.focus().addClass("active");
            }
            else {
                $('#search_results').find("li:first").focus().addClass("active");
            }
            return ;
        }
    });
});

and the style what i append is,

#search_results li.active { background:#000; color:#fff; }

here is another fiddle for up and down arrow key. https://jsfiddle.net/7h0pavzb/1/