Keyboard navigation with roving tabindex
Learn roving tabindex for web components: one Tab stop per widget, arrow keys in vertical and right-to-left layouts, Home, End, typeahead, and focusgroup.
- 01Give a group one Tab stopBuild a reusable roving tabindex helper that copes with items added, removed, and disabled later, and brings Tab back to the last item.
- 02Pick the right arrow keysUse Left and Right or Up and Down for each ARIA pattern, swap Left and Right on right-to-left pages, and add Home, End, and typeahead.
- 03Choose between the three waysKnow when to use a roving tabindex,
aria-activedescendant, or the newfocusgroupattribute, and what each can do across shadow roots.
How do you move focus with arrow keys in a web component?
Leaf and Kettle's menu page has a row of flavor buttons: Green, Black, Oolong, and Herbal. Ravi moves through pages with the keyboard. To reach the first tea card, he presses Tab five times: once for each flavor, and once more. Every new flavor adds one more press. How can the row cost him one press, and still let him reach every flavor?
Give the row one Tab stop. One button has tabindex="0", and every other button has tabindex="-1". The arrow keys move focus inside the row, and the 0 moves with it. This is called a roving tabindex.
You met it in lesson 10.2, inside the kit's tabs. This lesson turns it into a helper any component can use. It also adds columns, right-to-left pages, Home, End, and jumping by typing a letter. Here is the idea at its smallest:
<tea-flavors> <button tabindex="0">Green</button> <button tabindex="-1">Black</button> <button tabindex="-1">Oolong</button> <button tabindex="-1">Herbal</button></tea-flavors><script> class TeaFlavors extends HTMLElement { constructor() { super(); this.addEventListener("keydown", (event) => { const items = [...this.children]; const from = items.indexOf(event.target); const step = { ArrowRight: 1, ArrowLeft: -1 }[event.key]; if (from === -1 || !step) return; const to = items.at((from + step) % items.length); event.target.tabIndex = -1; to.tabIndex = 0; to.focus(); console.log("Focus:", to.textContent); }); } } customElements.define("tea-flavors", TeaFlavors);</script>- Lines 2 to 5 write each button's tabindex by hand. Only Green has 0, so only Green is in the Tab order.
- Line 11 listens for keys on the host. A key press goes to the focused button, then bubbles up to the host.
- Line 13 finds the button with focus. Line 14 turns Right Arrow into 1 and Left Arrow into -1. Line 15 lets every other key pass.
- Line 16 picks the button one step away. The
%sign brings the count back to 0 after the last button, andat(-1)means the last one. So the row goes around its ends. - Lines 17 to 19 are the three moves: the old button gets -1, the new button gets 0, and the new button gets focus.
Click Green, then press Right Arrow four times. It prints Focus: Black, Focus: Oolong, Focus: Herbal, and Focus: Green again. Now press Tab: focus leaves the row at once.
tabindex="0" is. The arrow keys reach the other three.At Leaf and Kettle's staff meeting, one microphone goes around the table. Only the person holding it may speak. When Meena is done, she hands it to Ravi, and Ravi speaks. Nobody grabs a second microphone.
- In real life: The one microphone at the table
- In JavaScript: The one item with
tabindex="0" - In real life: Only the holder may speak
- In JavaScript: Only that item is a Tab stop
- In real life: Handing it to the next person
- In JavaScript: Old item -1, new item 0
- In real life: The next person starts to speak
- In JavaScript:
focus()on the new item
A roving tabindex makes a widget one Tab stop. Exactly one item has tabindex="0", and the rest have -1. The arrow keys move the 0 to another item and focus it. So Tab leaves the widget at once, and brings you back to where you were.
Why it matters: keyboard users pay one key press for every Tab stop. A row that costs one press is a row they can pass quickly, and still use.
Why should a widget have only one Tab stop?
The ARIA Authoring Practices Guide, the APG, describes how keyboard users expect widgets to work. Its keyboard guide gives one rule that every platform shares:
- Tab and Shift+Tab move from one component to the next.
- The arrow keys move between the parts inside one component.
A component with several parts that take focus is a composite widget. Radio groups, tabs, menus, listboxes, and toolbars are all composite widgets. The APG says the Tab order should hold only one of their parts. Try both rows:
<button>Before</button><div> <button>Green</button> <button>Black</button> <button>Oolong</button> <button>Herbal</button></div><button>After</button><script type="module" src="tea-flavors.js"></script><script> document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>Click Before, then press Tab. It prints Focus: Green, Black, Oolong, Herbal, and only then After. Every button is a Tab stop. Click Black, press Tab until After, then Shift+Tab: focus comes back to Herbal, the button just before After.
- Line 2 is a plain box, or the flavor row. Line 7 closes it. Nothing else changes.
- Line 9 loads the flavor row's file. The next section opens it.
- Line 11 prints the text of each element that gets focus.
- The plain row prints Green, Black, Oolong, Herbal, and then After. Four flavors cost five presses.
- The flavor row prints
Focus: Green, thenFocus: After. The whole row costs one press.
Where does Tab land when you come back?
Now try the second step in the playground. Click Black, Tab out to After, then press Shift+Tab. The flavor row prints Focus: Black. The 0 stayed on Black when you left, so Tab brought you back there.
The APG lists where focus should land when Tab enters a composite widget. It depends on the widget:
- The item that had focus last, or the first item the first time. Grids work this way.
- The selected item, or the first item if none is selected. Radio groups (the checked radio), tabs, listboxes, and trees work this way.
- The first item. Toolbars and menubars work this way, and the APG lets them go back to the last item instead.
MDN's guide to keyboard widgets asks for the same thing: when someone tabs away and comes back, focus returns to the item they left. The flavor row does that. For a radio group or tabs, the 0 belongs on the checked or selected item instead, as the kit's tabs do.
Asha reads a book about tea on the train. When her stop comes, she puts a bookmark at her page. The next morning she opens the book at the bookmark, not at page one.
- In real life: The book
- In JavaScript: The widget
- In real life: The bookmark
- In JavaScript: The item with
tabindex="0" - In real life: Moving the bookmark as you read
- In JavaScript: The arrow keys moving the 0
- In real life: Opening the book again
- In JavaScript: Tab coming back into the widget
Why it matters: one stop per widget keeps the Tab order short. And coming back to the same item means nobody has to find their place twice.
Building a reusable roving tabindex helper
The APG's steps are always the same: the old item gets -1, the new item gets 0, and the new item gets focus. So the kit gets a helper for them, roving.js. It also covers three things the overview's code missed:
- Buttons added later need a tabindex too, or each one is a Tab stop of its own.
- A disabled button can't take focus, so the 0 must never sit on one.
- A click should move the 0 too. The APG says so, and MDN adds that a screen reader can move focus as well.
A component makes the helper with its host and a function that returns its items. Here is its core:
constructor(host, items, { vertical = false, wrap = true, typeaheadDelay = 500 } = {}) {
Object.assign(this, { host, items, vertical, wrap, typeaheadDelay });
host.addEventListener("focusin", (event) => this.#onFocusin(event));
host.addEventListener("keydown", (event) => this.#onKeydown(event));
}
/** Gives one item tabindex="0" and every other item "-1". Call it whenever the items change. */
update() {
const enabled = this.items().filter((item) => !item.matches(":disabled"));
if (!enabled.includes(this.#current)) this.#current = enabled[0] ?? null;
for (const item of this.items()) item.tabIndex = item === this.#current ? 0 : -1;
}
#onFocusin(event) {
const item = event.composedPath()[0];
if (!this.items().includes(item)) return;
this.#current = item;
this.update();
}- Line 1 takes the host, a function that returns the items, and three options. The next sections come back to the options.
- Line 2 keeps all five on the helper, so a component can change one later.
- Lines 3 and 4 listen on the host. Focus and key events from the items bubble up to it, even from inside a shadow root.
- Lines 8 to 12 are
update(). Line 9 leaves out disabled items::disabledmatches a button with thedisabledattribute. Line 10 keeps the current item if it's still enabled, or picks the first enabled one. Line 11 gives that item 0 and every other item -1. - Lines 14 to 19 run whenever an item gets focus: from Tab, a click, or a screen reader. Line 17 makes it the current item.
Line 15 reads the element that got focus, from the event's composed path. Why not document.activeElement? Lesson 9.3 showed that it gives the host when focus is in its shadow root. And a listener on the host sees event.target as the host for anything inside. The first node of the composed path, from lesson 9.1, is the real element either way.
Here is the flavor row's own file, which uses the helper:
import { RovingFocus } from "./roving.js";
class TeaFlavors extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML = `<style>:host { display: flex; gap: 8px; }</style><slot></slot>`;
const slot = this.shadowRoot.querySelector("slot");
const buttons = () => slot.assignedElements().filter((element) => element.localName === "button");
const roving = new RovingFocus(this, buttons);
slot.addEventListener("slotchange", () => roving.update());
new MutationObserver(() => roving.update()).observe(this, { subtree: true, attributeFilter: ["disabled"] });
}
}
customElements.define("tea-flavors", TeaFlavors);- Line 8 says which elements are items: the buttons the page put in the slot.
assignedElements()lists them, as lesson 8.3 showed. - Line 9 makes the helper.
- Line 10 calls
update()on everyslotchange. It fires when the buttons first arrive, and when one is added or removed, as lesson 8.4 showed. - Line 11 calls
update()when a button'sdisabledattribute changes. A MutationObserver watches for that, because the button stays in its slot and noslotchangefires.
Now watch the tabindex values as the buttons change:
<button id="before">Before</button><tea-flavors> <button>Green</button> <button>Black</button> <button>Oolong</button> <button>Herbal</button></tea-flavors><button id="add">Add Puer</button><button id="sell">Sell out Green</button><script type="module" src="tea-flavors.js"></script><script> const flavors = document.querySelector("tea-flavors"); const show = () => setTimeout(() => console.log([...flavors.children].map((button) => `${button.textContent} ${button.tabIndex}`).join(", "))); customElements.whenDefined("tea-flavors").then(show); document.querySelector("#add").addEventListener("click", () => { flavors.append(Object.assign(document.createElement("button"), { textContent: "Puer" })); show(); }); document.querySelector("#sell").addEventListener("click", () => { flavors.querySelector("button").disabled = true; show(); }); flavors.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>- Line 13 prints each button with its tabindex, after the helper has had its turn.
- Line 16 adds a Puer button. Line 20 disables the first button, Green.
- At first it prints
Green 0, Black -1, Oolong -1, Herbal -1. - Click Add Puer. It prints
Green 0, Black -1, Oolong -1, Herbal -1, Puer -1. The new button joins the row as -1. - Click Sell out Green. It prints
Green -1, Black 0, Oolong -1, Herbal -1, Puer -1. The 0 moved off the disabled button. - Click Before and press Tab. It prints
Focus: Black.
Without line 11, Green would keep the 0. Tab skips a disabled button, so it would skip the whole row. Exercise 5 shows that bug.
Sometimes a person should still find a button that can't be used. The APG says to mark it aria-disabled="true" then. That tells assistive technology the button is disabled, and the button can still take focus. The APG keeps disabled menu items, options, and tabs reachable this way. The helper only skips :disabled, so an aria-disabled button stays in the arrow path. Exercise 4 uses it.
Why it matters: real lists change. The helper keeps exactly one Tab stop however the buttons come, go, or switch off.
Which arrow keys should a vertical or horizontal widget use?
The APG's pattern pages say which arrows each widget uses: the toolbar, the radio group, the listbox, and the menu and menubar. Read each row across:
| Widget | Arrow keys that move focus | At the first and last item | Home and End |
|---|---|---|---|
| Toolbar | Left and Right. Up and Down when it's vertical. | It may wrap around. | They're optional. |
| Radio group | All four. Right and Down go forward, Left and Up go back. | It always wraps around. | The pattern doesn't list them. |
| Listbox | Up and Down. Left and Right when it's horizontal. | The pattern doesn't say it wraps. | They're optional, and strongly recommended past five options. |
| Menu | Up and Down. | It may wrap around. | They go to the first and last item when the arrows don't wrap. |
| Menubar | Left and Right. | It may wrap around. | They go to the first and last item when the arrows don't wrap. |
The rule underneath: a row uses Left and Right, and a column uses Up and Down. Of these widgets, only a radio group listens to all four arrows.
A screen reader can't see the layout, so the widget says it. aria-orientation is horizontal or vertical. A toolbar is horizontal unless it says otherwise, and a listbox vertical. A component sets it from its internals, with ariaOrientation, as lesson 13.2 set states.
The helper turns each key into a step with one small function:
/** Which way a key moves focus: 1 to the next item, -1 to the one before, "first", "last", or null. */
export function keyStep(key, { vertical = false, rtl = false } = {}) {
if (key === "Home") return "first";
if (key === "End") return "last";
const next = vertical ? "ArrowDown" : rtl ? "ArrowLeft" : "ArrowRight";
const back = vertical ? "ArrowUp" : rtl ? "ArrowRight" : "ArrowLeft";
if (key === next) return 1;
if (key === back) return -1;
return null;
}- Lines 3 and 4 turn Home and End into first and last. The section on typeahead comes back to them.
- Line 5 picks the key for next: Down in a column, Right in a row, and Left in a right-to-left row.
- Line 6 picks the key for back, the other way around.
- Lines 7 to 9 give 1 for next, -1 for back, and null for any other key. In a row, Up and Down give null.
The keydown listener uses that step:
#onKeydown(event) {
const item = event.composedPath()[0];
if (!this.items().includes(item) || event.altKey || event.ctrlKey || event.metaKey) return;
const enabled = this.items().filter((each) => !each.matches(":disabled"));
const from = enabled.indexOf(item);
const rtl = getComputedStyle(this.host).direction === "rtl";
const step = keyStep(event.key, { vertical: this.vertical, rtl });
let to;
if (step === "first") to = enabled[0];
else if (step === "last") to = enabled.at(-1);
else if (step !== null) to = this.wrap ? enabled.at((from + step) % enabled.length) : enabled[from + step];
else if (event.key.length === 1 && event.key !== " ") to = this.#typeahead(event, enabled, from);
if (!to) return;
event.preventDefault();
this.#current = to;
this.update();
to.focus();
}- Line 3 lets a key pass if it wasn't pressed on an item, or if Alt, Ctrl, or Cmd was held down.
- Lines 4 and 5 list the enabled items and find the one with focus. Line 7 asks for the step.
- Line 11 takes one step. With
wrapon,at()and%go around the ends, as in the overview. With it off, a step past the end finds nothing. - Line 13 stops when there's nowhere to go. Then the key keeps its normal job, like scrolling the page.
- Lines 14 to 17 move:
preventDefault()so the page doesn't scroll too, then the 0, then focus.
Now try three layouts of the same toolbar:
<tea-flavors> <button>Green</button> <button>Black</button> <button>Oolong</button> <button>Herbal</button></tea-flavors><script type="module"> import { RovingFocus } from "./roving.js"; class TeaFlavors extends HTMLElement { #internals = this.attachInternals(); constructor() { super(); this.#internals.role = "toolbar"; this.#internals.ariaOrientation = "horizontal"; this.attachShadow({ mode: "open" }).innerHTML = `<style>:host { display: flex; flex-direction: row; align-items: flex-start; gap: 8px; }</style><slot></slot>`; const slot = this.shadowRoot.querySelector("slot"); const roving = new RovingFocus(this, () => slot.assignedElements(), { vertical: false, wrap: true }); slot.addEventListener("slotchange", () => roving.update()); } } customElements.define("tea-flavors", TeaFlavors); document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>Click Green and press Left Arrow: Focus: Herbal, because the row wraps around. Right Arrow goes back to Green. Down and Up do nothing here, so they still scroll the page.
- Line 13 gives the host the role toolbar. Line 14 sets its orientation.
- Line 15 lays the buttons out in a row or a column.
- Line 17 passes
verticalandwrapto the helper.
- Across, wrapping: Left Arrow on Green prints
Focus: Herbal. Down and Up do nothing. - Across, stopping: Left Arrow on Green prints nothing. Right Arrow prints
Focus: Black. - Down, wrapping: Left and Right do nothing. Down Arrow prints
Focus: Black.
A lift goes between floors, so it has two buttons: Up and Down. Nobody looks for a Left button in a lift. In a long shop corridor, you walk left or right. A sign at the door tells you which one you're in.
- In real life: A lift between floors
- In JavaScript: A vertical widget
- In real life: Its Up and Down buttons
- In JavaScript: Up Arrow and Down Arrow
- In real life: A long shop corridor
- In JavaScript: A horizontal widget
- In real life: The sign that says Lift
- In JavaScript:
aria-orientation
- A toolbar of flavor buttons in a row.
- A toolbar with
aria-orientation="vertical", its buttons in a column. - A radio group for cup sizes.
- A listbox of teas, one under another.
- A menu that opens from a menu button.
- A menubar across the top of an app.
Sort each widget by the arrow keys the APG gives it.
Leaving keys to text boxes
A text box needs Left and Right to move its caret, and every letter to type. The APG's toolbar pattern says to avoid controls that need the toolbar's arrows. If one can't be avoided, keep only one, at the end. The helper leaves other elements' keys alone in three ways:
- It only acts on keys pressed on an item itself (line 3 of the keydown code).
- It lets keys pass when Alt, Ctrl, or Cmd is held, so shortcuts still work.
- It calls
preventDefault()only for a key it uses.
<tea-flavors> <button>Green</button> <button>Black</button> <button>Oolong</button> <button>Herbal</button> <input aria-label="Other flavor" placeholder="Other flavor"></tea-flavors><script type="module" src="tea-flavors.js"></script><script> document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent || event.target.placeholder)); document.addEventListener("input", (event) => console.log("Typed:", event.target.value));</script>- Line 6 is a text box for another flavor. It isn't a button, so it isn't one of the row's items.
- Line 10 prints each focus. Line 11 prints what the box holds after each change.
Click Herbal and press Tab: Focus: Other flavor. Type go: it prints Typed: g and Typed: go, and focus doesn't jump to Green. Press Left Arrow: the caret moves, and nothing prints. Shift+Tab goes back to Focus: Herbal.
Why it matters: the right keys make a widget feel familiar at once. And a widget that steals keys from a text box breaks typing.
How do arrow keys work in right-to-left layouts?
Arabic, Hebrew, Persian, and Urdu are written from right to left. On those pages, a row of buttons starts on the right. The next button is to the left of the first. So Left Arrow should move forward.
The APG's pattern pages name Left and Right as they work on a left-to-right page. The Open UI explainer for focusgroup, a feature this lesson comes back to, says it plainly: in right-to-left content, Left Arrow moves focus forward. Here is the flavor row on an Arabic page:
<div dir="rtl" lang="ar"> <tea-flavors> <button value="green">أخضر</button> <button value="black">أسود</button> <button value="oolong">أولونغ</button> <button value="herbal">أعشاب</button> </tea-flavors></div><script type="module" src="tea-flavors.js"></script><script> document.addEventListener("focusin", (event) => console.log("Focus:", event.target.value));</script>- Line 1 sets the direction with
dir="rtl", and the language withlang="ar". - Lines 3 to 6 say green, black, oolong, and herbal in Arabic. Each button's
valueis its name in English. - Line 11 prints that English name when a button gets focus.
Click the rightmost button. Press Left Arrow twice, then Right Arrow once. It prints Focus: green, Focus: black, Focus: oolong, and Focus: black. Left went forward, and Right went back.
Line 6 of the keydown code made that happen. It reads the host's direction, and line 5 of keyStep() swaps the keys. There are two ways to ask a host which way it runs:
host.matches(":dir(rtl)")follows thedirattribute, on the host or any of its parents. MDN notes that it ignores the CSSdirectionproperty.getComputedStyle(host).directionfollows CSS too, includingdir.
<div dir="ltr"> <tea-flavors> <button>Green</button> <button>Black</button> <button>Oolong</button> <button>Herbal</button> </tea-flavors></div><script type="module" src="tea-flavors.js"></script><script type="module"> const flavors = document.querySelector("tea-flavors"); console.log(":dir(rtl):", flavors.matches(":dir(rtl)"), "| direction:", getComputedStyle(flavors).direction); flavors.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>It prints :dir(rtl): false | direction: ltr. Green is on the left. Click Green and press Left Arrow: Focus: Herbal. Left goes back, and the row wraps to its last button.
- Line 1 is the box around the row. It's the only line that changes.
- Line 12 prints both answers.
- dir="ltr" prints
:dir(rtl): false | direction: ltr. Left Arrow on Green wraps back to Herbal. - dir="rtl" prints
:dir(rtl): true | direction: rtl. Left Arrow on Green goes forward to Black. - direction: rtl in CSS prints
:dir(rtl): false | direction: rtl. The row still runs right to left, and Left Arrow still goes to Black.
The CSS Writing Modes spec tells authors not to use the direction property in HTML pages, and to use dir. On a page that does, both answers agree. The helper reads the computed style anyway, because that's what lays out its row. Lesson 15.2, in Accessible components, covers direction in full.
A book printed in Arabic opens from what an English reader calls the back. To read on, you turn each page to the left. Both books have a next page. Only the hand movement swaps.
- In real life: The next page
- In JavaScript: The next item
- In real life: The front cover on the right
- In JavaScript: The first item on the right
- In real life: Turning the page to the left
- In JavaScript: Left Arrow moving forward
- In real life: The language the book is printed in
- In JavaScript:
dir="rtl"
Why it matters: for someone who reads right to left, Right Arrow going forward feels backwards. One line in the helper fixes it on every page.
How do Home, End, and typeahead work?
Lines 3 and 4 of keyStep() turn Home and End into first and last. Lines 9 and 10 of the keydown code go there. The APG makes them optional in a toolbar. For a listbox with more than five options, it strongly recommends them. In a menu, they reach the ends when the arrows don't wrap.
In a long list, you can also jump by typing. This is called typeahead. The APG's listbox pattern recommends it, most of all past seven options:
- Type one letter: focus moves to the next item whose name starts with it.
- Type several letters quickly: focus moves to the next item whose name starts with all of them.
A menu may jump on one letter too. The kit's flavor row does both. Line 12 of the keydown code sends each single character to this method, except Space, which presses the button:
#typeahead(event, enabled, from) {
if (event.timeStamp - this.#typedAt > this.typeaheadDelay) this.#typed = "";
this.#typedAt = event.timeStamp;
this.#typed += event.key.toLowerCase();
const start = this.#typed.length === 1 ? from + 1 : from;
const order = [...enabled.slice(start), ...enabled.slice(0, start)];
return order.find((each) => each.textContent.trim().toLowerCase().startsWith(this.#typed));
}- Line 2 starts a new word if more than
typeaheadDelaymilliseconds passed since the last letter. It compares each key event's timeStamp, the moment the key was pressed. So there's no timer to start or clear. - Line 3 keeps this key's time. Line 4 adds the letter, in lowercase. The default wait is 500 ms, the same as the APG's own listbox example.
- Line 5 picks where to start looking. For a first letter, it starts after the current item, so a second B goes on to the next B. For more letters, it starts at the current item, which may still match.
- Line 6 puts the items in that order, going around to the start. Line 7 finds the first name that fits.
<tea-flavors> <button>Green</button> <button>Black</button> <button>Blooming</button> <button>Oolong</button> <button>Herbal</button></tea-flavors><script type="module" src="tea-flavors.js"></script><script> document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>Line 10 prints each focus. Pause between these steps:
- Click Green. Press End, then Home:
Focus: Herbal, thenFocus: Green. - Press H:
Focus: Herbal. - Press B:
Focus: Black. Press B again:Focus: Blooming, the next flavor with B. - Press Home, wait, then type
bloquickly. It printsFocus: Green,Focus: Black, thenFocus: Blooming. Black fits b and bl. Only Blooming fits blo.
A thick dictionary has little letter tabs cut into its edge. Press your thumb on G, and it opens at the G words. Then you read on to the word you want: gr, gre, green.
- In real life: Pressing your thumb on the G tab
- In JavaScript: Typing one letter
- In real life: The book opening at the G words
- In JavaScript: Focus on the next item starting with G
- In real life: Reading on, letter by letter
- In JavaScript: Typing more letters quickly
- In real life: Closing the book and starting over
- In JavaScript: Half a second passing
Why it matters: in a list of twenty teas, typing a letter beats twenty presses of Down Arrow. And Home and End stop the page from scrolling away.
When should you use aria-activedescendant instead?
There's a second way to manage focus inside a widget. With aria-activedescendant, focus never moves. It stays on the container, often a text box. The attribute names the active item by its id, and the APG says screen readers treat that item as focused. It's like a tour guide who stays at the front of the group and points at each painting.
Your code has more to do then. It draws the ring on the active item, and scrolls it into view. With a roving tabindex, the browser scrolls the focused item into view for you.
So use it when focus has to stay where you type. A combobox is a text box with a list of suggestions. You type, and Down Arrow moves through the suggestions without leaving the box. Everywhere else, a roving tabindex is simpler.
In a web component, there's a catch. An id only points inside its own tree, as lesson 13.3 showed for labels. The element property, ariaActiveDescendantElement, can point out of a shadow root to the page. It can't point into one. MDN calls this the reflected element reference scope.
<tea-suggest> <div role="option" id="green">Green</div> <div role="option" id="black">Black</div></tea-suggest><script> class TeaSuggest extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = ` <input id="box" role="combobox" aria-label="Flavor" aria-controls="list" aria-expanded="true"> <div id="list" role="listbox"><slot></slot></div>`; } } customElements.define("tea-suggest", TeaSuggest); const box = document.querySelector("tea-suggest").shadowRoot.getElementById("box"); box.setAttribute("aria-activedescendant", "black"); console.log("By id:", box.ariaActiveDescendantElement); box.ariaActiveDescendantElement = document.getElementById("black"); console.log("By element:", box.ariaActiveDescendantElement.textContent);</script>- Lines 2 and 3 are the page's options, with the ids green and black.
- Line 10 is a combobox text box in the shadow root. Line 11 is a listbox around the slot.
- Line 16 sets the attribute to the id black. Line 17 prints
By id: null. The id is looked up in the shadow root, and black isn't there. - Line 18 sets the property to the option itself. Line 19 prints
By element: Black.
Chrome's accessibility tree agrees. The combobox named Flavor has an active descendant: the option Black.
aria-activedescendant, focus stays in the text box, and the box names the active option. From a shadow root, only the element property can name the page's option.Read each row across to compare the two ways:
| Question | Roving tabindex | aria-activedescendant |
|---|---|---|
| Where is focus? | On the item. It moves with every arrow press. | On the container, like a text box. It never moves. |
| Who scrolls the item into view? | The browser, when focus() moves. | Your code. |
| Who draws the ring? | The browser, through :focus-visible. | Your code, on the active item. |
| Does it work across shadow roots? | Yes. It only uses tabindex and focus(). | Only with ariaActiveDescendantElement, and only pointing out of a shadow root. |
| When is it the right choice? | Toolbars, radio groups, tabs, menus, and most listboxes. | When focus has to stay in a text box, as in a combobox. |
Why it matters: an id that points across a shadow root fails without an error. The screen reader hears no active item at all.
What is the focusgroup attribute?
Sites write this same code again and again. The focusgroup attribute asks the browser to do it instead. The Chrome 150 release notes describe what it gives a widget: arrow-key moves, one Tab stop, and memory of the last focused item, with no script at all.
<button>Before</button><div focusgroup="toolbar wrap" aria-label="Flavors"> <button>Green</button> <button>Black</button> <button>Oolong</button> <button>Herbal</button></div><button>After</button><script> console.log("focusgroup:", "focusGroup" in HTMLElement.prototype); document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>- Line 2 is the whole roving tabindex.
toolbarnames the pattern, andwraplets the arrows go around the ends. - Line 10 prints whether the browser has the feature.
In Chrome, it prints focusgroup: true. Click Before, then press Tab, Right Arrow, Tab, and Shift+Tab. It prints Green, Black, After, and Black: one stop, with memory. Left Arrow twice prints Green, then Herbal. Chrome's accessibility tree shows the box as a toolbar named Flavors. In Chrome, the arrows also follow dir="rtl", and the attribute works on a custom element with slotted buttons.
The explainer lists what the value can hold:
- A pattern first:
toolbar,tablist,radiogroup,listbox,menu, ormenubar. - Then, if you like:
inlineorblockfor one axis,wrapornowrap, andnomemoryto start at the first item every time. focusgroup="none"takes an element out, andfocusgroupstartmarks the item Tab enters first.
Only Chrome and Edge have it, from version 150. The HTML Standard doesn't include it yet: the change is an open pull request. Mozilla's position is positive. On WebKit's issue, its reviewers like the general idea but have concerns about the interaction model, and haven't taken a position. Chrome Platform Status tracks it.
In Firefox and Safari, the page prints focusgroup: false, and every button is a Tab stop. So the kit keeps its helper. Why it matters: focusgroup is where the platform is going, and the helper works today in every browser.
Adding a flavor toolbar to the tea kit
The kit gets two new files. tea-kit/roving.js is the helper from this lesson, word for word. tea-kit/tea-flavors.js is the flavor row, finished. Open its tab to see:
- Line 40 gives the host the role toolbar, from its internals.
- Line 45 makes the helper with the slotted buttons. Lines 46 and 47 call
update()when buttons come, go, or switch off. - Lines 51 to 55 copy the
labelattribute to the toolbar's name, and theorientationattribute to the helper and toariaOrientation. - Line 12 draws the ring with
::slotted(:focus-visible), in the ring color from lesson 14.1.
Here it filters the menu:
<link rel="stylesheet" href="tea-kit/tokens.css"><style>ul { list-style: none; padding: 0; display: grid; gap: 8px; }</style><tea-flavors label="Flavors"> <button>Green</button> <button>Black</button> <button>Oolong</button> <button>Herbal</button></tea-flavors><ul> <li data-flavor="Green"><tea-card name="Sencha" price="4"></tea-card></li> <li data-flavor="Black"><tea-card name="Assam" price="3"></tea-card></li> <li data-flavor="Oolong"><tea-card name="Tieguanyin" price="6"></tea-card></li> <li data-flavor="Herbal"><tea-card name="Chamomile" price="3"></tea-card></li></ul><script type="module"> import "./tea-kit/index.js"; const flavors = document.querySelector("tea-flavors"); flavors.addEventListener("click", (event) => { const flavor = event.target.closest("button")?.textContent; if (!flavor) return; for (const button of flavors.querySelectorAll("button")) button.ariaPressed = String(button.textContent === flavor); for (const item of document.querySelectorAll("li")) item.hidden = item.dataset.flavor !== flavor; console.log("Showing:", flavor); });</script>- Line 3 names the toolbar Flavors. Lines 10 to 13 tag each tea card with its flavor.
- Line 18 listens for clicks. Enter and Space on a button click it too. Line 21 marks the picked button as pressed, so screen readers say which filter is on.
- Line 22 hides every tea of another flavor.
Click Green: Showing: Green. Press Right Arrow twice and Enter: Showing: Oolong. Press Tab: focus goes straight to the Tieguanyin card's - button. In Chrome's tree, the toolbar is named Flavors, its orientation is horizontal, and Oolong is pressed.
The JSDoc and custom-elements.json document tea-flavors: its label and orientation attributes, its slot, its row part, and --tea-focus-ring. This version of the kit is kitAfter142. For the keyboard events behind it, see Keyboard and focus on the JavaScript path.
Common mix-ups
- "Every button in a toolbar should be a Tab stop." No. A composite widget is one Tab stop. The arrow keys move inside it.
- "tabindex="-1" puts an item out of reach." No. Tab skips it, but
focus()and clicks still reach it. That's how the arrows move to it. - "Tab always enters a roving group at the first item." No. It enters wherever the 0 is: the item you left, or the selected one.
- "Right Arrow always means next." No. In a right-to-left row, Left Arrow means next.
- ":dir(rtl) sees the CSS direction." No. It follows the
dirattribute only. The computeddirectionfollows both. - "A disabled item can keep the 0." No. Tab skips a disabled button, and with it the whole widget. Move the 0 when an item is disabled.
- "aria-activedescendant with an id works from a shadow root to the page." No. An id only points inside its own tree.
ariaActiveDescendantElementcan point out, never in. - "focusgroup works in every browser." No. Only Chrome and Edge have it, from version 150.
Practice exercises
For each one, ask which item holds the 0, and which way the key points. Then check in the result.
In the overview's row, click Green and press Left Arrow. What does it print?
<tea-flavors> <button tabindex="0">Green</button> <button tabindex="-1">Black</button> <button tabindex="-1">Oolong</button> <button tabindex="-1">Herbal</button></tea-flavors><script> class TeaFlavors extends HTMLElement { constructor() { super(); this.addEventListener("keydown", (event) => { const items = [...this.children]; const from = items.indexOf(event.target); const step = { ArrowRight: 1, ArrowLeft: -1 }[event.key]; if (from === -1 || !step) return; const to = items.at((from + step) % items.length); event.target.tabIndex = -1; to.tabIndex = 0; to.focus(); console.log("Focus:", to.textContent); }); } } customElements.define("tea-flavors", TeaFlavors);</script>Focus: Herbal. From Green, the step is -1. -1 % 4 is -1, and items.at(-1) is the last button, so the row wraps to Herbal.
Click Green, at the right end, and press Right Arrow. What does the page print?
<div dir="rtl"> <tea-flavors> <button>Green</button> <button>Black</button> <button>Oolong</button> <button>Herbal</button> </tea-flavors></div><script type="module" src="tea-flavors.js"></script><script> document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>Focus: Herbal. The row runs right to left, so Right Arrow is the back key. Back from the first button goes around to the last.
Click After and press Shift+Tab. Focus lands on Herbal, not on the button with the 0. Fix the flavor row, not the page. Which flavor does Shift+Tab from After focus then?
<button>Before</button><tea-flavors> <button>Green</button> <button>Black</button> <button>Oolong</button> <button>Herbal</button></tea-flavors><button>After</button><script type="module" src="tea-flavors.js"></script><script> document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script><button>Before</button><tea-flavors> <button>Green</button> <button>Black</button> <button>Oolong</button> <button>Herbal</button></tea-flavors><button>After</button><script type="module" src="tea-flavors.js"></script><script> document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>Focus: Green. The page stays the same. Only the tea-flavors.js tab changes: line 10 is back, slot.addEventListener("slotchange", () => roving.update());. Without it, no button has a tabindex until one gets focus, so all four are Tab stops, and Shift+Tab lands on the last one.
Oolong is sold out, and the arrows skip it. Keep it reachable, so screen reader users learn it exists. What does Right Arrow on Black print then?
<tea-flavors> <button>Green</button> <button>Black</button> <button disabled>Oolong</button> <button>Herbal</button></tea-flavors><script type="module" src="tea-flavors.js"></script><script> document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent)); document.addEventListener("click", (event) => { if (event.target.matches("[aria-disabled=true]")) console.log(event.target.textContent, "is sold out"); });</script><tea-flavors> <button>Green</button> <button>Black</button> <button aria-disabled="true">Oolong</button> <button>Herbal</button></tea-flavors><script type="module" src="tea-flavors.js"></script><script> document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent)); document.addEventListener("click", (event) => { if (event.target.matches("[aria-disabled=true]")) console.log(event.target.textContent, "is sold out"); });</script>Focus: Oolong. Only line 4 changes. aria-disabled="true" doesn't match :disabled, so the helper keeps Oolong in the arrow path, and assistive technology still hears that it's disabled. Press Enter on it: the page prints Oolong is sold out.
Click Herbal, then Sell out Herbal. Now click Before and press Tab: focus jumps past the whole row. Fix the flavor row. What does that Tab print then?
<button>Before</button><tea-flavors> <button>Green</button> <button>Black</button> <button>Oolong</button> <button>Herbal</button></tea-flavors><button id="sell">Sell out Herbal</button><script type="module" src="tea-flavors.js"></script><script> document.querySelector("#sell").addEventListener("click", () => { document.querySelector("tea-flavors button:last-child").disabled = true; }); document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script><button>Before</button><tea-flavors> <button>Green</button> <button>Black</button> <button>Oolong</button> <button>Herbal</button></tea-flavors><button id="sell">Sell out Herbal</button><script type="module" src="tea-flavors.js"></script><script> document.querySelector("#sell").addEventListener("click", () => { document.querySelector("tea-flavors button:last-child").disabled = true; }); document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>Focus: Green. The page stays the same. The tea-flavors.js tab gets line 11 back: a MutationObserver on the host, with { subtree: true, attributeFilter: ["disabled"] }, that calls update(). Then the 0 leaves Herbal the moment it's disabled.
The pot sizes stand in a column, and Down Arrow does nothing. Give them one Tab stop with the helper, moving with Up and Down. Click Cup and press Down Arrow twice. What does the second press print?
<tea-sizes> <button>Cup</button> <button>Mug</button> <button>Small pot</button> <button>Large pot</button></tea-sizes><script type="module"> import { RovingFocus } from "./roving.js"; class TeaSizes extends HTMLElement { #internals = this.attachInternals(); constructor() { super(); this.#internals.role = "toolbar"; this.#internals.ariaOrientation = "vertical"; this.attachShadow({ mode: "open" }).innerHTML = `<style>:host { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; }</style><slot></slot>`; // Give the sizes one Tab stop, with Up and Down. } } customElements.define("tea-sizes", TeaSizes); document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script><tea-sizes> <button>Cup</button> <button>Mug</button> <button>Small pot</button> <button>Large pot</button></tea-sizes><script type="module"> import { RovingFocus } from "./roving.js"; class TeaSizes extends HTMLElement { #internals = this.attachInternals(); constructor() { super(); this.#internals.role = "toolbar"; this.#internals.ariaOrientation = "vertical"; this.attachShadow({ mode: "open" }).innerHTML = `<style>:host { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; }</style><slot></slot>`; const slot = this.shadowRoot.querySelector("slot"); const roving = new RovingFocus(this, () => slot.assignedElements(), { vertical: true }); slot.addEventListener("slotchange", () => roving.update()); } } customElements.define("tea-sizes", TeaSizes); document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>Focus: Small pot. Lines 16 to 18 replace the comment: they find the slot, make the helper with { vertical: true }, and call update() on slotchange. Down Arrow goes from Cup to Mug to Small pot.
Check your understanding
For each question, ask where the 0 is, and which way the row runs.
Question 1 of 8A toolbar of four buttons uses a roving tabindex. How many times does Tab stop in it?
Choose an answer to see the explanation.
Question 2 of 8Focus is on Black, the button with
tabindex="0". Ravi presses Right Arrow. What does a roving tabindex do?Choose an answer to see the explanation.
Question 3 of 8Which arrow keys move focus in a vertical listbox?
Choose an answer to see the explanation.
Question 4 of 8A horizontal toolbar sits inside
<div dir="rtl">. Which key moves focus to the next button?Choose an answer to see the explanation.
Question 5 of 8A page sets
direction: rtlwith CSS and writes nodirattribute. What doesflavors.matches(":dir(rtl)")give?Choose an answer to see the explanation.
Question 6 of 8The flavors are Green, Black, Blooming, Oolong, and Herbal. Focus is on Green. Asha types b, l, o quickly. Where is focus then?
Choose an answer to see the explanation.
Question 7 of 8A text box in a shadow root sets
aria-activedescendant="black", and#blackis an option on the page. What does the box'sariaActiveDescendantElementgive?Choose an answer to see the explanation.
Question 8 of 8Which browsers have the
focusgroupattribute?Choose an answer to see the explanation.
Key takeaways
- A composite widget is one Tab stop. Tab moves between widgets, and the arrow keys move inside one.
- A roving tabindex gives one item
tabindex="0"and the rest -1, and moves the 0 with focus. - Tab comes back to the item that holds the 0: the last one used, or the selected one.
- Update the 0 on
slotchange, when an item is disabled, and on everyfocusin. - Read the focused item from
event.composedPath()[0], notdocument.activeElement. - Rows use Left and Right, columns use Up and Down, and
aria-orientationsays which. - In a right-to-left row, Left Arrow moves forward. Read the computed direction.
- Home and End go to the ends. Typeahead jumps to the next name that starts with the letters typed.
- Use
aria-activedescendantwhen focus must stay in a text box. From a shadow root, setariaActiveDescendantElement. focusgroupdoes all of this with no script, in Chrome and Edge from 150.
Remember the one-liner.
One Tab stop per widget, one item with the 0, and arrow keys that follow the layout and the writing direction.
Sources
The facts on this page come from these standards, docs, and posts:
- Developing a Keyboard Interface: keyboard navigation inside components, W3C WAI-ARIA Authoring Practices.
- Developing a Keyboard Interface: managing focus with a roving tabindex, W3C WAI-ARIA Authoring Practices.
- Keyboard-navigable JavaScript widgets: Technique 1, roving tabindex, MDN.
- Toolbar pattern, W3C WAI-ARIA Authoring Practices.
- Event: composedPath() method, MDN.
- Developing a Keyboard Interface: focusability of disabled controls, W3C WAI-ARIA Authoring Practices.
- Radio Group pattern, W3C WAI-ARIA Authoring Practices.
- Listbox pattern, W3C WAI-ARIA Authoring Practices.
- Menu and Menubar pattern, W3C WAI-ARIA Authoring Practices.
- ElementInternals: ariaOrientation property, MDN.
- Scoped focusgroup explainer, Open UI.
- :dir(), MDN.
- CSS Writing Modes Level 3: the direction property, W3C.
- Listbox example script: clearKeysSoFarAfterDelay, W3C WAI-ARIA Authoring Practices on GitHub.
- Event: timeStamp property, MDN.
- Developing a Keyboard Interface: managing focus with aria-activedescendant, W3C WAI-ARIA Authoring Practices.
- Element: ariaActiveDescendantElement property, MDN.
- Reflected attributes: reflected element reference scope, MDN.
- Chrome 150 release notes: Focusgroup, Chrome for Developers.
- Focusgroup, Chrome Platform Status.
- [focusgroup] Add the focusgroup attribute, whatwg/html#11723, WHATWG.
- Focusgroup, standards position, Mozilla.
- focusgroup attribute, standards position, WebKit.
- browser-compat-data, MDN.
Coming next: Accessible tabs. It brings the kit's tabs up to the full ARIA tabs pattern, with roles, states, and keys.