Skip to content Skip to sidebar Skip to footer

How To Navigate Between Dynamically Populated Li Elements Using Up Or Down Keys

I have an
    unordered list with dynamically populated
  • list elements with data taken from database using JQuery .ajax function:
    • Pr

Solution 1:

Using a CSS helper class --focus for this:

var pr = ["Product1", "Product2", "Product3", "Product4", "Product5", "Product6"];
for (var option in pr) {
  var newLi = document.createElement("li");
  newLi.innerHTML = pr[option];
  $("#here").append(newLi);
}

var currentFocus;

$(document).on("keyup", function(e) {
  if (e.keyCode === 38 || e.keyCode === 40) {
    e.preventDefault();
    
    var children = $("#here").children();
    if (currentFocus === undefined) {
      currentFocus = 0;
    } else {
      currentFocus += e.keyCode === 38 ? -1 : 1;
      currentFocus < 0 && (currentFocus = children.length - 1);
      currentFocus >= children.length && (currentFocus = 0);
    }
    children.removeClass("--focus");
    children.eq(currentFocus).addClass("--focus"); 
  }

});
#here {
  background-color: white;
  width: 175px;
  height: 300px;
  border: 1px solid grey;
  padding: 0px 0px 10px 10px;
}
#here li:hover,
#here li.--focus {
  background: #ccc;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="here">
</ul>

Solution 2:

You can try something like that -

in order to make the li focusable it should have a tabindex.

You can add an event listener to the ul capturing clicks on li

var pr= ['Product1', 'Product2', 'Product3', 'Product4', 'Product5', 'Product6'];
$("#here").append(
    pr.map(function(product){
        return $('<li tabindex="0">'+product+'</li>')
    })).on('keydown','li', function(e) {
        if (e.keyCode == 40) {        
            $(this).next().focus();
        }
        if (e.keyCode == 38) {        
            $(this).prev().focus();
        }
});     

Post a Comment for "How To Navigate Between Dynamically Populated Li Elements Using Up Or Down Keys"