How to focus on a non input element?

Sami C.
2 min readDec 30, 2018

--

The Situation

Today I stumbled upon a problem, I wanted to make my <li> list items focusable. I found out that there is an attribute called tabindex. In my use-case I wanted to make the list item focusable by using the arrow keys, not the tab key.

TL;DR

add tabindex=’0' property if you want your non input element to be reachable via non sequential keyboard navigation.

add tabindex=’-1' property if you want your non input element to be focusable, but not reachable via sequential keyboard navigation.

What is the tabindex?

The tabindex global attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation

Explaning the order Order

By tabbing we will move through the first input, then the first div, then the second div, and finally the last input.

It is not recommended to give positive values to your elements. You will end up jumping between them, and it will be confusing to manipulate between your element’s tabindexattribute values. Instead, focus on writing them in a suitable DOM sequence.

How Do I use this without the tab key?

As I stated above, I do not want my items focusable by using the tab key. So in my use-case I ended up adding

<li tabindex='-1'>Item 1</li>

This means that the li is focusable, but not by tabbing, if that makes any sense. So the next step is to focus my list item inside my webcomponent:

var focusedListItemIndex = 0;this.element.shadowRoot.querySelectorAll('li')[focusedListItemIndex].focus();

and whenever I used my key arrows I incremented or decremented the focusedListItemIndex.

Verdict

Important to know is that, without the tabindex attribute on the <li> element, the focus method in javascript will not work on the html element.

Leave any questions down below and Thanks for reading!

--

--

Sami C.
Sami C.

Written by Sami C.

Freelance Software Engineer

Responses (1)