Szekelygobe
Szekelygobe

Reputation: 2697

Navigating ul list element with keyboard

So I have one text input for search and a suggestion ul list loaded via ajax:

    $(document).keydown(function(e) {
      var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
      if ($('#suggestion_list li').length > 0) {
        if (key == 40) {
          e.preventDefault();
          if ($('#suggestion_list li a:focus').length == 0) {
            $('#suggestion_list li a').first().focus();
          } else {
            $("#suggestion_list li a").next().focus();
          }
        }
      } else {
        $(this).focus();
      }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="hsng_search_inpt" type="text" id="hsng_search_text" value="" autocomplete="off">

<ul id="suggestion_list">
  <li class="mp_search_suggest_element" item_val="item name 1">
    <a href="http://some_url1.html">
      <span>item name 1</span>
    </a>
  </li>
  <li class="mp_search_suggest_element" item_val="item name 2">
    <a href="http://some_url2.html">
      <span>item name 2</span>
    </a>
  </li>
  <li class=" mp_search_suggest_element" item_val="item name 3">
    <a href="http://some_url3.html">
      <span>item name 3</span>
    </a>
  </li>
</ul>

So my goal is to navigate through the ul li elements and on enter to go to the url inside the li. On arrow down pressed on the keyboard (code 40) I can select the fist a in the list but can't get to the next one. How can I set focus to the next li > a ? Thanks.

Upvotes: 0

Views: 1558

Answers (1)

Bindrid
Bindrid

Reputation: 3735

you cant really set focus and remove focus on an li. So the code below simulates it. you can see it work here: https://jsfiddle.net/bindrid/cmeeskpu/29/

$(document).on("keydown", function(evt){

    if(evt.keyCode == 40){

        var cs = $(".selected");
        // if none are selected, select the first on
        if(cs.length == 0){
            cs = $("#suggestion_list li:first");
            cs.addClass("selected")
           return;
        }
        // get next li. If no li rotate to  the first one again.
        var ns = cs.next("li");
        if(ns.length == 0){
            ns = $("#suggestion_list li:first");
        }
       cs.removeClass("selected");
       ns.addClass("selected");
   } 
   if(evt.keyCode == 13){
        window.location.href = $(".selected a").attr("href");
    }
})

css class for simulating selected

.selected{ 
    background-color: green;
    color:white;
  }
 .selected a { color:white}

Upvotes: 1

Related Questions