Reputation: 1
Upvotes: 0
Views: 659
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