Kundan Munda
Kundan Munda

Reputation: 1

How to navigate/traverse through collection of HTML '<li>' elements using Keyboard Arrow Keys using JavaScript and keep track of the <li> element?

  1. How to traverse through a HTML
  2. element through JS?
  3. How to keep track of the traversed
  4. element?
  5. How to pass an object via a function call whenever we hit the 'Enter' key?

Upvotes: 0

Views: 659

Answers (1)

Rahul Shah
Rahul Shah

Reputation: 2043

You need to use the tabindex property to make the li focusable and the keydown handler to handle events. The code below should give a rought idea. To keep track of which element you are on, you can use the tabIndex or e.target.value or a data-attribute.

<ul>
  <li tabindex="0" onkeydown="moveFocus(event)">A</li>
  <li tabindex="1" onkeydown="moveFocus(event)">B</li>
  <li tabindex="2" onkeydown="moveFocus(event)">C</li>
  <li tabindex="3" onkeydown="moveFocus(event)">D</li>
</ul>
<script>
  const tabbableItems = Array.from(document.querySelectorAll("ul>li"))
  
function moveFocus(e){
  let currentIndex = e.currentTarget.getAttribute("tabIndex")
  if(e.key === "ArrowDown"){
        currentIndex++
  } else if (e.key === "ArrowUp"){
        currentIndex--
  }
   const toFocus = tabbableItems.find(el => 
       el.getAttribute("tabIndex") == currentIndex
   )

   if(toFocus){
     toFocus.focus()
   }
}
</script>

Upvotes: 0

Related Questions