mrtnmgs
mrtnmgs

Reputation: 1552

Tabindex 0 on focusable element (button)

I've noticed the following pattern on several occasions in a code base I'm currently working on:

<button tabindex="0">A button</button>
<ul tabindex="-1">...

Of course, tabindex="-1" on the ul prevents focus, but what's the point of setting tabindex=0 on a button? Isn't this element already focusable by default?

Upvotes: 1

Views: 5681

Answers (2)

TimB
TimB

Reputation: 1000

Just to elaborate some more on the use of tabindex and what this means in this context:

Tabindex="0" means: Focusable with tab key and from script (using element.focus()), and inserted into the natural taborder (aka the order logically following the DOM). As this is the default behaviour of buttons, you can ditch <button tabindex="0"> as nonsense and bloatcode.

Tabindex greater than 0 assigns a custom taborder. So, if you say <button tabindex="1">, the button will always get focused first when using tab, regardless of the DOM-structure. This method is discouraged.

Tabindex="-1" says you can't focus it using tab, but the JavaScript element.focus() function will work. On an ul this only makes sense if you want to focus it from script at some point. Else this is bloatcode as well, and also assigns an unintended role.

Upvotes: 1

slugolicious
slugolicious

Reputation: 17435

Both uses of tabindex are superfluous. The <button> doesn't need it to receive focus and the <ul> doesn't need it to prevent focus. Looks like a rookie wrote that code.

Upvotes: 5

Related Questions