completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

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.

By the end, you can
  • 01
    Give 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.
  • 02
    Pick 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.
  • 03
    Choose between the three waysKnow when to use a roving tabindex, aria-activedescendant, or the new focusgroup attribute, 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:

A flavor row that moves the 0 with Left and RightPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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, and at(-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.

Two rows of Tab stops. Top, a plain row of buttons: Before, Green, Black, Oolong, Herbal, After, with a Tab arrow between each, labelled five presses of Tab. Bottom, a roving tabindex: Before, then a tea-flavors box holding Green with tabindex 0 and Black, Oolong, and Herbal with -1, then After. One Tab arrow goes into the box and one goes out, labelled two presses of Tab. A note in the box says the arrow keys move inside.a plain row of buttonsBeforeGreenBlackOolongHerbalAfter5 presses of Taba roving tabindexBeforetea-flavorsGreenBlackOolongHerbal0-1-1-1the arrow keys move insideAfterTabTab2 presses of Tab
In a plain row, every button is a Tab stop. With a roving tabindex, only the button with tabindex="0" is. The arrow keys reach the other three.
Real-life analogyPassing the microphone

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
The main idea

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:

Playground: how many Tab stops?
Four flavor buttons between Before and AfterPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Five presses to get past

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.

Only lines 2 and 7 change. Click Before in the result, then press Tab until focus reaches After. Then click Black, press Tab until After, and press Shift+Tab.
  • 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, then Focus: 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.

Real-life analogyA bookmark in a book

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:

The helper's constructor, update(), and focus listener, from roving.jsJavaScript
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: :disabled matches a button with the disabled attribute. 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:

The flavor row, from tea-flavors.jsJavaScript
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 every slotchange. 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's disabled attribute changes. A MutationObserver watches for that, because the button stays in its slot and no slotchange fires.

Now watch the tabindex values as the buttons change:

Adding a flavor and selling one outPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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.
  1. At first it prints Green 0, Black -1, Oolong -1, Herbal -1.
  2. Click Add Puer. It prints Green 0, Black -1, Oolong -1, Herbal -1, Puer -1. The new button joins the row as -1.
  3. Click Sell out Green. It prints Green -1, Black 0, Oolong -1, Herbal -1, Puer -1. The 0 moved off the disabled button.
  4. 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.

Two rows of four flavor buttons. Top, before the key press: Green -1, Black 0 with focus, Oolong crossed out as disabled, Herbal -1. A curved arrow labelled Right Arrow goes from Black over Oolong to Herbal. Bottom, after the press: Green -1, Black -1, Oolong still disabled, Herbal 0 with focus.Right ArrowGreenBlackOolongHerbal-10, focusdisabled-1after the pressGreenBlackOolongHerbal-1-1disabled0, focus
The helper leaves disabled buttons out, because they can't take focus. Right Arrow on Black jumps over Oolong to Herbal, and the 0 moves with it.

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:

Which keys does each pattern use?
WidgetArrow keys that move focusAt the first and last itemHome and End
ToolbarLeft and Right. Up and Down when it's vertical.It may wrap around.They're optional.
Radio groupAll four. Right and Down go forward, Left and Up go back.It always wraps around.The pattern doesn't list them.
ListboxUp 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.
MenuUp and Down.It may wrap around.They go to the first and last item when the arrows don't wrap.
MenubarLeft 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 each key moves, from roving.jsJavaScript
/** 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:

Moving focus on a key press, from roving.jsJavaScript
#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 wrap on, 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:

Playground: which arrow keys move focus?
A toolbar that passes its layout to the helperPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Left and Right, around the ends

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 17 changes, and lines 14 and 15 too for the column. Click Green in the result, then press Left Arrow, Right Arrow, Down Arrow, and Up Arrow.
  • 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 vertical and wrap to 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.
Real-life analogyThe buttons in a lift

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
Which arrow keys move focus?
  • 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.
Try it yourself
0 of 6 correct

Sort each widget by the arrow keys the APG gives it.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

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.
A text box at the end of the flavor rowPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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:

The flavor row on a right-to-left pagePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 1 sets the direction with dir="rtl", and the language with lang="ar".
  • Lines 3 to 6 say green, black, oolong, and herbal in Arabic. Each button's value is 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 the dir attribute, on the host or any of its parents. MDN notes that it ignores the CSS direction property.
  • getComputedStyle(host).direction follows CSS too, including dir.
Playground: which way is next?
The flavor row in a box with a writing directionPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Left to right

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.

Only line 1 changes. Read the first line the page prints, then click Green and press Left Arrow.
  • 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.

Two rows of the same four flavors. Top, dir="ltr": Green, Black, Oolong, Herbal from left to right, and an arrow from Green to Black labelled next is Right Arrow. Bottom, dir="rtl": the row starts on the right, so it reads Herbal, Oolong, Black, Green from left to right, and an arrow from Green to Black points left, labelled next is Left Arrow.dir="ltr"GreenBlackOolongHerbalnext is Right Arrowdir="rtl"HerbalOolongBlackGreennext is Left Arrow
On a right-to-left page, the first button sits on the right, and the next one is to its left. So Left Arrow moves forward and Right Arrow moves back.
Real-life analogyTurning the pages of an Arabic book

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, from roving.jsJavaScript
#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 typeaheadDelay milliseconds 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.
Five flavors, two with BPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…

Line 10 prints each focus. Pause between these steps:

  1. Click Green. Press End, then Home: Focus: Herbal, then Focus: Green.
  2. Press H: Focus: Herbal.
  3. Press B: Focus: Black. Press B again: Focus: Blooming, the next flavor with B.
  4. Press Home, wait, then type blo quickly. It prints Focus: Green, Focus: Black, then Focus: Blooming. Black fits b and bl. Only Blooming fits blo.
Real-life analogyThe letter tabs on a dictionary

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.

A text box in a shadow root names a page optionPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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.

Two halves. Left, roving tabindex: three cards, Green, Black, and Oolong, with focus on Black, and a note that each arrow press moves focus. Right, aria-activedescendant: a window titled shadow root holds a text box card, and focus stays in it. Below the window are the page's options, Green and Black. An arrow goes from the text box out of the shadow root to Black, labelled ariaActiveDescendantElement.roving tabindexGreenBlackOolongfocus is on Blackeach arrow press moves focusaria-activedescendantshadow root<input id="box">focus stays hereGreenBlackariaActiveDescendantElementnames the page's Black option
With a roving tabindex, focus itself moves to the option. With 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:

Roving tabindex or aria-activedescendant?
QuestionRoving tabindexaria-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.

The flavor row with focusgroup and no scriptPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 2 is the whole roving tabindex. toolbar names the pattern, and wrap lets 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, or menubar.
  • Then, if you like: inline or block for one axis, wrap or nowrap, and nomemory to start at the first item every time.
  • focusgroup="none" takes an element out, and focusgroupstart marks 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 label attribute to the toolbar's name, and the orientation attribute to the helper and to ariaOrientation.
  • Line 12 draws the ring with ::slotted(:focus-visible), in the ring color from lesson 14.1.

Here it filters the menu:

The kit's flavor toolbar over four teasPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 dir attribute only. The computed direction follows 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. ariaActiveDescendantElement can 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.

Exercise 1 · Warm-upLeft from the first flavor

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>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upRight Arrow in a right-to-left row

    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>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeComing in backwards

      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>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeKeep a sold-out flavor findable

        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>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeThe row that Tab skips

          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>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeA column of pot sizes

            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>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask where the 0 is, and which way the row runs.

              The roving tabindex quiz · 8 questionsScore: first tries count
              1. 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.

              2. 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.

              3. Question 3 of 8Which arrow keys move focus in a vertical listbox?

                Choose an answer to see the explanation.

              4. 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.

              5. Question 5 of 8A page sets direction: rtl with CSS and writes no dir attribute. What does flavors.matches(":dir(rtl)") give?

                Choose an answer to see the explanation.

              6. 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.

              7. Question 7 of 8A text box in a shadow root sets aria-activedescendant="black", and #black is an option on the page. What does the box's ariaActiveDescendantElement give?

                Choose an answer to see the explanation.

              8. Question 8 of 8Which browsers have the focusgroup attribute?

                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 every focusin.
              • Read the focused item from event.composedPath()[0], not document.activeElement.
              • Rows use Left and Right, columns use Up and Down, and aria-orientation says 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-activedescendant when focus must stay in a text box. From a shadow root, set ariaActiveDescendantElement.
              • focusgroup does 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:

              Coming next: Accessible tabs. It brings the kit's tabs up to the full ARIA tabs pattern, with roles, states, and keys.

              CompleteFrontend Clear concepts. Working examples.