rk8785
rk8785

Reputation: 189

Element is not taking focus Javascript

I have a list whose structure looks like this

<ul>
   <li tabindex =0> hello <li>
   <li> hi </li>
   <li> bye </li>
   <li> goodbye </li>
</ul.

When the focus is on hello and I press keydown the focus should move to hi. I do this programmatically by setting the focus. I have a listener set on the list which track the key events

handleKeyevent (e){
    if(e.item.keyCode == 38){
         document.activeElement.nextElementSibling.focus();
    }
}

but the focus remains on hello. On debugging I saw that the next element (li tag) had tabindex = -1 which should not be a problem as the focus still can be set programmatically. The only way I was able to set the focus on next element was to change the tabindex =0 but that is not technically required.

I have written this JSFIDLE where you can see that on load i try to set the focus on id =6 but it does not get the focus. But try to to change id to 1 and load. The new element recieves focus.

Upvotes: 1

Views: 101

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

You need to set a tabindex on any element which could be focused.

<ul>
    <li tabindex="0">hello</li>
    <li tabindex="0">hi</li>
    <li tabindex="0">bye</li>
    <li tabindex="0">goodbye</li>
</ul>

Upvotes: 2

Related Questions