UmarAbbasKhan UmarAbbasKhan - 2 months ago 6
CSS Question

how to navigate between dynamically populated li elements using up or down keys

I have an

<ul>
unordered list with dynamically populated
<li>
list elements with data taken from database using JQuery .ajax function:

<ul id="here">
<li>Product1</li>
<li>Product2</li>
<li>Product3</li>
<li>Product4</li>
<li>Product5</li>
<li>Product6</li>
</ul>


I can hover over these using following css code:

#here{
position: fixed;
background-color: white;
width:175px;
height:300px;
border: 1px solid grey;
display:none;
padding:0px 0px 10px 10px;
}
#here li:hover {
background: #ccc;
cursor: pointer;
}


The Javascript and JQuery written for populating the
<li>
elements is:

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


but I need to be able to move up and down among these
<li>
elements using keyboard up and down keys. Can anyone guide me how can I do this?

Answer

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>

Comments