completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Adding selection and events to the tabs

Add keyboard navigation to web component tabs: clicks, arrow keys, roving tabindex, an attribute and property in sync, and a change event for real picks.

By the end, you can
  • 01
    Select tabs the way the APG asksPick a tab with a click, the arrow keys, Home, and End, with a roving tabindex, and choose automatic or manual activation on purpose.
  • 02
    Keep the attribute and the property in syncKeep the number in one place, so selected and selectedIndex always agree, with no loop, sensible results for bad values, and no value lost before the upgrade.
  • 03
    Announce a person's pickDispatch tea-change only for clicks and keys, after the panel shows, and keep nested tabs from fooling an outer listener.

How do you make web component tabs respond to clicks and keys?

Asha puts the brewing guide from lesson 10.1 on the tablet at the counter. A customer taps Black. Nothing happens. Another customer uses only the keyboard. She presses Tab and lands on Green. The arrow keys do nothing either. The tabs show the right steps, but only the page's own code can pick them.

Ravi checks the API card from lesson 10.1. Two promises are still open. The reader should be able to pick a tab. And the page should hear about it, through a tea-change event. How do tabs listen for clicks and keys? And how does the page hear about a pick, but not about its own changes?

Tabs become selectable when the component listens for clicks and arrow keys on its own row of tabs. Each pick becomes a new selectedIndex, and the selected attribute stays the one place the number lives. After the panel shows, the component dispatches a change event, but only for a person's pick.

The keys come from the APG, the ARIA Authoring Practices Guide you met in lesson 10.1. Here are the finished tabs. Click a tab, then try the arrow keys, Home, and End:

The finished tabs, with each pick printedPop out in the code editor (opens in a new tab)HTML
<tea-tabs>  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <button slot="tab">Oolong</button>  <section slot="panel">Steep green tea for 2 minutes.</section>  <section slot="panel">Steep black tea for 4 minutes.</section>  <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script type="module">  import "./tea-tabs.js";  document.querySelector("tea-tabs").addEventListener("tea-change", (event) => {    console.log("Picked", event.tab.textContent);  });</script>
ResultLoading…
  • Lines 1 to 8 are lesson 10.1's tabs: three buttons, then three sections.
  • Line 11 loads the finished class. It's in the tea-tabs.js tab.
  • Lines 12 to 14 listen for tea-change and print the tab the reader picked.

Click Black. The console prints Picked Black, and Black's steps show. Press Right: it prints Picked Oolong. Press Right again, and the row wraps around to the start: Picked Green. Home and End jump to the first and the last tab.

Real-life analogyTurning the menu to the page you point at

Leaf and Kettle's menu is a big book on a stand at the counter. You point at a tea, and Ravi turns the menu to its page. Say "next", and he turns one page on. At the last page, "next" takes him back to the first. When you pick, he calls it to the kitchen. When he tidies the menu himself, he calls nothing.

In real life: Pointing at a tea
In JavaScript: Clicking a tab
In real life: Saying "next" or "back"
In JavaScript: Right Arrow and Left Arrow
In real life: Ravi turning to that page
In JavaScript: #choose() setting selectedIndex
In real life: Calling your pick to the kitchen
In JavaScript: Dispatching tea-change
The main idea

The tabs listen on their own row. A click or a key becomes a new selectedIndex. That writes the selected attribute, and the attribute draws the tabs. Only then, and only for a person's pick, does tea-change go out.

The lesson finishes the tabs in four parts:

  1. Managing selection: clicks, keys, and one Tab stop for the whole row.
  2. Keeping selected and selectedIndex in sync, even for bad or early values.
  3. Sending tea-change at the right moments, even with tabs inside tabs.
  4. Finishing touches: a name, a focus ring, and tabs that come and go.

Selecting a tab with a click

The tabs are the page's own buttons, slotted into the tab row in the shadow root. So where should the component listen? Open the tea-tabs.js tab of the first example. Lines 60 to 62, at the end of the constructor, add two listeners to the tab row. One is for click, one for keydown.

A click on a slotted tab passes through its slot on the way up. So a listener in the shadow root hears it, and the tab is still the target. Lesson 9.1 showed it. A click inside a panel never passes the tab row, so the row hears only tabs. Here are the three methods a click uses:

Picking a tab on click, from tea-tabs.jsJavaScript
#tabs() {
  return this.shadowRoot.querySelector('slot[name="tab"]').assignedElements();
}

#onClick(event) {
  const index = this.#tabs().findIndex((tab) => tab.contains(event.target));
  if (index !== -1) this.#choose(index);
}

#choose(index) {
  if (index === this.selectedIndex) return;
  this.selectedIndex = index;
  this.dispatchEvent(new TeaChangeEvent(index, this.#tabs()[index]));
}
  • Lines 1 to 3, #tabs(), give the elements in the tab slot, in page order, as in lesson 8.3.
  • Line 6 finds the tab that holds the click's target. contains() is true for the tab itself and for anything inside it, like a span around its text.
  • Line 7 hands that tab's position to the next method. A click on the row's empty space finds no tab.
  • Lines 10 to 14 are #choose(). Line 11 stops if the tab is already selected.
  • Line 12 sets selectedIndex. That writes the attribute, and the tabs draw again.
  • Line 13 tells the page. The events section below explains it.

Enter and Space need no code of their own. A button already turns them into a click. So a keyboard user can pick a tab too.

Westbrook Johnson points out a catch. Hold Enter down on a button, and its click repeats, as long as the key is down. Line 11 makes that harmless. After the first click, the tab is already selected, so the repeats do nothing.

Which keys should a tabs component support?

The APG's tabs pattern lists the keys for a row of tabs that runs across the page:

  • Right Arrow moves to the next tab. On the last tab, it goes back to the first.
  • Left Arrow moves to the previous tab. On the first tab, it goes to the last.
  • Home moves to the first tab, and End to the last. The APG marks these two optional. The kit has them.
  • Down Arrow and Up Arrow do nothing in the tabs. They keep scrolling the page.

Each key gives a new position. A small function works it out:

Where each key goes, from tea-tabs.jsJavaScript
/** The position of the tab a key moves focus to, counting from 0. Other keys give null. */
function keyTarget(key, from, count) {
  if (key === "ArrowRight") return (from + 1) % count;
  if (key === "ArrowLeft") return (from - 1 + count) % count;
  if (key === "Home") return 0;
  if (key === "End") return count - 1;
  return null;
}
  • Line 2 takes the key's name, the focused tab's position, and the number of tabs. The name comes from KeyboardEvent.key, like "ArrowRight", as the JavaScript course's keyboard lesson showed.
  • Line 3 adds 1. The % sign gives the remainder after dividing by count. So with three tabs, 3 % 3 is 0: past the last tab, you land on the first.
  • Line 4 takes 1 away. Adding count first keeps the number from going below 0, so the first tab wraps to the last. The JavaScript course wrapped a list the same way.
  • Lines 5 and 6 are Home and End.
  • Line 7 gives null for every other key, Down and Up included.

The keydown listener uses it:

Moving with the keys, from tea-tabs.jsJavaScript
#onKeydown(event) {
  const tabs = this.#tabs();
  const from = tabs.indexOf(event.target);
  const to = keyTarget(event.key, from, tabs.length);
  if (from === -1 || to === null) return;
  event.preventDefault();
  tabs[to].focus();
  this.#choose(to);
}
  • Line 3 finds the focused tab. A key press goes to the element that has focus, so that's the target.
  • Line 4 asks keyTarget() where to go.
  • Line 5 stops if focus isn't on one of this row's tabs, or if the key isn't one of the four.
  • Line 6 calls preventDefault(), so Home and End don't also scroll the page.
  • Line 7 moves focus to the new tab, and line 8 picks it.

Down and Up never reach line 6, so they still scroll. That's why preventDefault() comes after the check, not before it.

Should a tab be picked as soon as it gets focus?

Line 8 makes the arrow keys pick the tab right away. The APG calls this automatic activation. The other way is manual activation. There, the arrow keys only move focus, and Enter or Space picks the tab. Try both:

Playground: automatic or manual activation?
What the arrow keys do in tea-tabs.jsJavaScript
#onKeydown(event) {
  const tabs = this.#tabs();
  const from = tabs.indexOf(event.target);
  const to = keyTarget(event.key, from, tabs.length);
  if (from === -1 || to === null) return;
  event.preventDefault();
  tabs[to].focus();
  this.#choose(to);
}
The tabs, with each pick printedPop out in the code editor (opens in a new tab)HTML
<tea-tabs>  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <button slot="tab">Oolong</button>  <section slot="panel">Steep green tea for 2 minutes.</section>  <section slot="panel">Steep black tea for 4 minutes.</section>  <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script type="module">  import "./tea-tabs.js";  document.querySelector("tea-tabs").addEventListener("tea-change", (event) => {    console.log("Picked", event.tab.textContent);  });</script>
ResultLoading…
Try it yourself
Focus and the pick move together

Click Green, then press Right twice. Each key moves focus and picks the tab, so the console prints Picked Black, then Picked Oolong, and Oolong's steps show. Enter then prints nothing more: Oolong is already picked.

Only line 8 of #onKeydown() changes, in the tea-tabs.js tab too. Click a tab in the Result first, so the keys reach it.

The APG recommends automatic activation when the panels show without a noticeable delay. That usually means the panels are already on the page. When a panel must load from a server, every arrow press would wait for it. The APG's keyboard guide calls that devastating for keyboard and screen reader users. Manual activation lets them move along the row first, and load only the tab they want.

The tea shop's panels are already on the page, so the kit picks automatic activation on purpose. Compare the two:

Automatic or manual activation: read each row as a question
QuestionAutomatic activationManual activation
What do Left and Right do?They move focus and pick the tab.They only move focus.
When does the panel change?As soon as a tab gets focus.When you press Enter or Space.
When should you choose it?When the panels are already on the page and show at once.When showing a panel takes time, like loading it from a server.
Which one does tea-tabs use?This one. Its panels are already on the page.Not this one. It would only slow the tabs down.

What is roving tabindex?

Pressing Tab moves focus from one control to the next. Should Tab visit every tab? The APG says no. A row of tabs is one stop on the page. Tab goes in, the arrow keys move inside, and Tab goes on. Two lines in #render() do it:

One Tab stop for the row, from tea-tabs.jsJavaScript
tab.setAttribute("role", "tab");tab.setAttribute("aria-selected", String(selected));tab.setAttribute("aria-controls", panel.id);tab.tabIndex = selected ? 0 : -1;panel.setAttribute("role", "tabpanel");panel.setAttribute("aria-labelledby", tab.id);if (!panel.hasAttribute("tabindex")) panel.tabIndex = 0;panel.hidden = !selected;
  • Line 4 gives the selected tab tabindex="0" and every other tab -1. The JavaScript course showed what they mean: 0 puts an element in the Tab order, and -1 lets code focus it while Tab skips it.
  • Line 7 gives a panel tabindex="0". The APG asks for it when a panel holds no focusable element, like these, which hold only text. If the page gave a panel its own tabindex, line 7 leaves it alone.
  • The other lines are lesson 10.1's roles and ids.

The 0 moves when the selection moves, from tab to tab. That's why it's called a roving tabindex. The APG's keyboard guide gives the steps: the old element gets -1, the new one gets 0, and the new one gets focus. #render() does the first two. Line 7 of the keydown code does the third.

Where Tab goes, with Black selectedPop out in the code editor (opens in a new tab)HTML
<button>Before</button><tea-tabs selected="1">  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <button slot="tab">Oolong</button>  <section slot="panel">Steep green tea for 2 minutes.</section>  <section slot="panel">Steep black tea for 4 minutes.</section>  <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs><button>After</button> <script type="module">  import "./tea-tabs.js";  document.addEventListener("focusin", (event) => {    const role = event.target.getAttribute("role") ?? event.target.localName;    console.log(role + ":", event.target.textContent);  });</script>
ResultLoading…
  • Lines 1 and 10 are page buttons, before and after the tabs.
  • Line 2 starts the tabs on Black.
  • Lines 14 to 17 print the role and the text of each element that gets focus. focusin bubbles, so one listener on the document hears them all.

Click Before, then press Tab three times. The console prints button: Before, tab: Black, tabpanel: Steep black tea for 4 minutes., and button: After. Tab came in at Black, the selected tab, not at Green. Then it went to the panel, then out. Press Shift+Tab twice to walk back: the panel, then Black.

Why does Tab go from a tab to a panel in another slot? Lesson 9.3 showed that slotted elements take their turn where their slot is. The tab slot comes before the panel slot, so the tabs come first.

Six cards in a row: Before, then the tabs Green, Black and Oolong, then Black panel, then After. Under the tabs are their tabindex values, minus 1, 0 and minus 1, and 0 under the panel. Arrows labelled Tab curve from Before to Black, from Black to Black panel, and from the panel to After. A note under the tabs says Left, Right, Home, and End move between them.TabTabBeforeGreenBlackOolongBlack panelTabAfter-10-10Left, Right, Home, and End move between these
With Black selected, Tab stops at Black, then at its panel, then at After. The numbers are each one's tabindex. Green and Oolong have -1, so Tab skips them, and the arrow keys reach them instead.
Real-life analogyOne bus stop for the whole market

A bus stops once at the town market. You get off and walk from stall to stall. When you're done, you get back on, and the bus goes on to its next stop. It never stops at every stall. And this market moves its stop each week, to the stall you bought from last.

In real life: The one bus stop at the market
In JavaScript: The one tab with tabindex="0"
In real life: Walking from stall to stall
In JavaScript: The arrow keys
In real life: The stop by the stall you chose last
In JavaScript: Tab landing on the selected tab
In real life: The bus going on to the next stop
In JavaScript: Tab moving on to the panel

How do you keep an attribute and a property in sync?

The selected attribute and the selectedIndex property are two ways to say one number. web.dev's checklist asks that they stay in sync both ways: set one, and the other follows. MDN calls such a property reflected, as lesson 5.1 built for the tea label.

There's a trap. A tempting class keeps the number in a field. Its setter writes the attribute, and its attributeChangedCallback() copies the attribute back into the property. Now each one calls the other. Lesson 3.4 watched that circle end in a RangeError. web.dev calls the problem reentrancy. Its fix guards one direction: only the setter writes. The kit's tabs have worked that way since lesson 10.1:

The callback, the getter, and the setter, from tea-tabs.jsJavaScript
attributeChangedCallback(name, oldValue, newValue) {
  if (oldValue === newValue) return;
  this.#render();
}

/** Which tab is selected, counting from 0. Reflects the selected attribute. */
get selectedIndex() {
  const last = Math.max(this.#tabs().length - 1, 0);
  return Math.min(toNonNegativeInteger(this.getAttribute("selected"), 0), last);
}

set selectedIndex(value) {
  this.setAttribute("selected", value);
}
  • Lines 1 to 4 are the callback. The browser calls it for every change to an observed attribute, as MDN explains. It only draws. It never sets the property, so it can't start a circle.
  • Lines 7 to 10 are the getter. It reads the attribute every time and keeps no copy, so it can't fall behind.
  • Lines 12 to 14 are the setter. It only writes the attribute.

A click goes through the same door. #choose() sets selectedIndex, so a person's pick writes the attribute too. This page counts the writes for each kind of change:

One write for each changePop out in the code editor (opens in a new tab)HTML
<tea-tabs>  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <button slot="tab">Oolong</button>  <section slot="panel">Steep green tea for 2 minutes.</section>  <section slot="panel">Steep black tea for 4 minutes.</section>  <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script type="module">  import "./tea-tabs.js";  const tabs = document.querySelector("tea-tabs");  const writes = new MutationObserver(() => {});  writes.observe(tabs, { attributeFilter: ["selected"] });  function report(who) {    const count = writes.takeRecords().length;    console.log(`${who}: attribute ${tabs.getAttribute("selected")}, property ${tabs.selectedIndex}, writes ${count}`);  }  tabs.selectedIndex = 2;  report("Property");  tabs.setAttribute("selected", "0");  report("Attribute");  tabs.addEventListener("tea-change", () => report("Person"));</script>
ResultLoading…
  • Lines 13 and 14 make a MutationObserver, from lesson 8.4, that notes each write of selected.
  • Line 16 calls takeRecords(). It hands over the notes so far and clears them, so each report counts only its own writes.
  • Lines 19 and 21 change the tab with the property, then with the attribute.
  • Line 23 reports after each pick by a person.

As the page loads, the console prints Property: attribute 2, property 2, writes 1 and Attribute: attribute 0, property 0, writes 1. Click Black, and it prints Person: attribute 1, property 1, writes 1. Each change writes the attribute once. So attributeChangedCallback() runs once, and nothing echoes back.

Three cards on the left: a click or a key, selectedIndex = 1, and setAttribute(). The click leads to #choose(1). From #choose(1), one arrow goes down to selected equals 1, and one goes right to tea-change, labelled only for a person. The other two cards lead straight to selected equals 1. From there an arrow leads to #render(), labelled draws again, and on to Black shows, labelled the panel.three ways ina click or a keyselectedIndex = 1setAttribute()#choose(1)tea-changeonly for a personselected="1"#render()Black showsdraws againthe panel
Every way in ends at the selected attribute, the one place the number lives. Writing it runs attributeChangedCallback(), which draws the tabs. Only a click or a key goes through #choose(), which then sends tea-change.
Real-life analogyOne board for today's tea

Leaf and Kettle writes today's tea on one chalkboard by the door. Asha and Ravi both write on it, and everyone reads it. Nobody copies it into a notebook. If they did, someone would copy the board into the notebook, someone else would copy the notebook back onto the board, and the copying would never end.

In real life: The chalkboard by the door
In JavaScript: The selected attribute
In real life: Writing on the board
In JavaScript: The setter
In real life: Reading the board
In JavaScript: The getter
In real life: Brewing whatever the board says
In JavaScript: attributeChangedCallback() drawing the tabs

What should selectedIndex do with a number that names no tab?

A page can write anything in an attribute: selected="7" on three tabs, selected="-1", or selected="two". The tabs must still show one panel. Lesson 10.1's getter already turned a missing or unreadable value into 0, with the reader from lesson 5.2. But 7 is readable, just too big. With lesson 10.1's file, selected="7" hides every panel.

Lines 8 and 9 of the sync code fix that:

  • Line 8 finds the last tab's position. Math.max(…, 0) keeps it at 0 while there are no tabs yet.
  • Line 9 reads the attribute, then keeps it at or below that last position with Math.min().
Playground: a number that names no tab
The attribute the page wrote, and the tab the getter picksPop out in the code editor (opens in a new tab)HTML
<tea-tabs selected="7">  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <button slot="tab">Oolong</button>  <section slot="panel">Steep green tea for 2 minutes.</section>  <section slot="panel">Steep black tea for 4 minutes.</section>  <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script type="module">  import "./tea-tabs.js";  const tabs = document.querySelector("tea-tabs");  console.log("selected:", tabs.getAttribute("selected"));  console.log("selectedIndex:", tabs.selectedIndex);</script>
ResultLoading…
Try it yourself
A number past the last tab

There are only three tabs, so the last one is tab 2. The getter keeps the number at or below it and gives back 2: Oolong shows. The attribute still says 7, what the page wrote.

Only line 1 changes. The kit's tea-tabs.js is in its own tab.

Look at the first line each time. The attribute still says what the page wrote. The getter never rewrites it. It only reads it sensibly. Built-in elements work this way too. A <progress> bar can't show more than its max:

A progress bar keeps its value in rangePop out in the code editor (opens in a new tab)HTML
<progress max="3" value="7"></progress> <script>  const progress = document.querySelector("progress");  console.log("value:", progress.value);  console.log("attribute:", progress.getAttribute("value"));</script>
ResultLoading…

Line 1 asks for 7 on a bar whose max is 3. Line 5 prints value: 3, and line 6 prints attribute: 7. The HTML Standard says the value property gives back the value kept between 0 and max. The attribute keeps what the page wrote. The tabs follow the same rule. So the callback never has to write, and there's still no circle.

The rule also helps when tabs come and go. If the page removes the selected last tab, the getter picks the new last tab. The finishing touches below show it.

What if the page sets selectedIndex before the class loads?

A page's own script can run before tea-tabs.js arrives. Then selectedIndex = 2 lands on a plain element, as a property of its own. Nolan Lawson describes what happens next: after the upgrade, that own property hides the class's setter, so the setter never runs. Lesson 4.2 fixed this for the tea price with the upgrade-property pattern. The tabs use it too:

connectedCallback() with the upgrade-property pattern, from tea-tabs.jsJavaScript
connectedCallback() {  if (!this.hasAttribute("role")) this.setAttribute("role", "presentation");  this.#upgradeProperty("selectedIndex");  this.#render();}
  • Line 2 is lesson 10.1's role.
  • Line 3 is new. #upgradeProperty() finds an own selectedIndex, deletes it, and sets it again, so the setter runs now. It's the kit's same four-line method from lesson 4.2.
  • Line 4 draws.
A selectedIndex set before the class loadsPop out in the code editor (opens in a new tab)HTML
<tea-tabs>  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <button slot="tab">Oolong</button>  <section slot="panel">Steep green tea for 2 minutes.</section>  <section slot="panel">Steep black tea for 4 minutes.</section>  <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script>  document.querySelector("tea-tabs").selectedIndex = 2;</script><script type="module">  import "./tea-tabs.js";  const tabs = document.querySelector("tea-tabs");  console.log("selected:", tabs.getAttribute("selected"));  console.log("Own property left:", Object.hasOwn(tabs, "selectedIndex"));</script>
ResultLoading…
  • Line 11 is in a plain script. It runs as soon as the browser reads it. The module on line 13 waits until the page is read, so the class loads later.
  • Line 16 prints selected: 2. The setter ran during the upgrade.
  • Line 17 prints Own property left: false. The page's own property is gone.

Oolong shows. Without line 3 of connectedCallback(), the page prints selected: null and Own property left: true. Oolong still shows, because #render() reads that own property. But the setter stays hidden: click Black, and Oolong's steps stay. Exercise 4 has that bug.

When should a web component fire a change event?

The page wants to know when the reader picks a tea, to update a label or remember the choice. Lesson 5.3 gave the rule. Dispatch events for what happened without the page, like a click. Don't dispatch for changes the page made through a property or an attribute. Lit's docs use a menu as the example: an event when the user picks an item, none when the page sets the selected item.

That's why the dispatch lives in #choose(), and only the click and keydown listeners call #choose(). Here is the event's class, near the top of tea-tabs.js:

The tea-change event class, from tea-tabs.jsJavaScript
/** Fired by tea-tabs when a person picks another tab. */
export class TeaChangeEvent extends Event {
  static type = "tea-change";

  constructor(index, tab) {
    super(TeaChangeEvent.type, { bubbles: true, composed: true });
    /** The new tab's position, counting from 0. */
    this.index = index;
    /** The new tab. */
    this.tab = tab;
  }
}
  • Line 2 extends Event, as lesson 5.3 recommended. Justin Fagnani argues for it too: fields on the event read better than a detail object.
  • Line 3 keeps the name, tea-change, in one place. A page can write TeaChangeEvent.type.
  • Line 6 makes it bubble and be composed.
  • Lines 8 and 10 carry the new tab's position and the tab itself.

Why composed? Lesson 9.2 gave the rule. An event that belongs to your public API, which a page needs wherever your element sits, bubbles and is composed. tea-change is on the API card. If another component puts the tabs in its own shadow root, the page still hears the pick, as it hears the card's tea-add.

The page's own change stays quietPop out in the code editor (opens in a new tab)HTML
<tea-tabs>  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <button slot="tab">Oolong</button>  <section slot="panel">Steep green tea for 2 minutes.</section>  <section slot="panel">Steep black tea for 4 minutes.</section>  <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script type="module">  import "./tea-tabs.js";  const tabs = document.querySelector("tea-tabs");  tabs.addEventListener("tea-change", (event) => {    const shown = tabs.querySelector('[role="tabpanel"]:not([hidden])');    console.log(`Picked ${event.index}, ${event.tab.textContent}: ${shown.textContent}`);  });  tabs.selectedIndex = 2;  console.log("The page picked", tabs.selectedIndex);</script>
ResultLoading…
  • Lines 13 to 16 print each pick: its position, its tab, and the panel that shows right now.
  • Line 17 picks Oolong from the page's own script. Line 18 prints what it picked.

As it loads, the console prints only The page picked 2. No tea-change: the page already knows. Click Black, and it prints Picked 1, Black: Steep black tea for 4 minutes. Press Home: Picked 0, Green: Steep green tea for 2 minutes.

The listener already sees the new panel. That's the other half of lesson 5.3's rule: update first, then dispatch. Lit's docs agree: fire the event after the element updates. In the click code, line 12 sets selectedIndex. The attribute's callback draws the tabs before the setter returns. So by line 13, the panel shows.

Real-life analogyTelling the kitchen about a new order

When a customer changes their order, Ravi calls it through to the kitchen. When the kitchen swaps a tea itself, because one ran out, Ravi doesn't call it back to them. They already know. And he calls only after he has written the new ticket, so the cook who looks at it sees the new order.

In real life: A customer changing their order
In JavaScript: A click or a key
In real life: Ravi calling it to the kitchen
In JavaScript: Dispatching tea-change
In real life: The kitchen swapping a tea itself
In JavaScript: The page setting selectedIndex
In real life: Writing the ticket first
In JavaScript: Drawing the tabs before dispatching

Now sort some changes. Which ones send the event?

Does tea-change fire?
  • The reader clicks Black while Green is selected
  • The reader presses Right on Oolong, the last tab
  • The reader presses End on Green
  • The reader presses Enter on the tab that's already selected
  • The page runs tabs.selectedIndex = 1
  • The page runs tabs.setAttribute("selected", "2")
  • The page removes the selected tab, so Black shows instead
Try it yourself
0 of 7 correct

Sort each change by whether the tabs dispatch tea-change for it.

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

Why does an outer listener hear the inner tabs' events?

Asha wants brewing steps inside the Green tab: Heat, then Steep. She puts a second tea-tabs in Green's panel. The page listens for tea-change on the outer tabs, #teas, to know which tea the reader is looking at. Try it:

Playground: tabs inside tabs
Brewing steps inside the Green tabPop out in the code editor (opens in a new tab)HTML
<tea-tabs id="teas">  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <section slot="panel">    <tea-tabs>      <button slot="tab">Heat</button>      <button slot="tab">Steep</button>      <section slot="panel">Heat the water until it steams.</section>      <section slot="panel">Steep the leaves for 2 minutes.</section>    </tea-tabs>  </section>  <section slot="panel">Steep black tea for 4 minutes.</section></tea-tabs> <script type="module">  import "./tea-tabs.js";  const teas = document.querySelector("#teas");  teas.addEventListener("tea-change", (event) => {    // No check yet.    console.log("Tea:", event.tab.textContent);  });</script>
ResultLoading…
Try it yourself
The outer listener hears the inner tabs

Click Steep, then Black. The console prints Tea: Steep, then Tea: Black. Steep isn't a tea. It came from the brewing steps inside Green's panel, and it bubbled up to #teas.

Only line 19 changes. Lines 5 to 10 are the brewing steps, a tea-tabs inside Green's panel.

With no check, clicking Steep prints Tea: Steep. The inner tabs dispatched tea-change, and it bubbled. The inner tabs sit in the page's own tree, inside Green's panel, inside #teas. So the event passes #teas on its way up, and the listener can't tell it from its own.

A window for the outer tabs, #teas, with the tabs Green and Black. Inside it, a window for Green panel holds the inner tabs, Heat and Steep, labelled inner tea-tabs. An arrow labelled tea-change leads from Steep out of both windows to a tag, the #teas listener. Under the tag: event.target, the inner tabs.#teasGreenBlackGreen panelHeatSteepinner tea-tabstea-change#teaslistenerevent.target:the inner tabs
The brewing steps are tabs inside Green's panel, in the page's own tree. Their tea-change bubbles up past #teas, so its listener hears Steep. event.target tells the two apart.

Cory LaViska describes the same problem with Shoelace's dialogs and dropdowns, which share event names. His fix is the one on line 19: check that event.target is the element you listen on. Comparing event.target with event.currentTarget, the element whose listener is running, works too. He also explains why a name for each tag, like tea-tabs-change, wouldn't help. The same tag can sit inside itself, as it does here.

Inside the component, the problem never starts. The tabs listen on their own tab row. A click on Steep travels up through the inner row, Green's panel, and the outer panel slot. It never passes the outer tab row. So the outer tabs stay on Green.

Real-life analogyWhich kettle is whistling?

Ravi has a big kettle on the counter. Asha sets a small one next to it. A whistle sounds, and Ravi reaches for his big kettle. But the small one whistled. Now he looks to see which kettle it is before he pours.

In real life: A whistle
In JavaScript: A tea-change event
In real life: Ravi's big kettle
In JavaScript: The outer tabs, #teas
In real life: The small kettle
In JavaScript: The brewing steps inside Green's panel
In real life: Looking to see which kettle it is
In JavaScript: Checking event.target

What finishing touches do accessible tabs need?

The tabs pick, move focus, and announce. A few small things finish them. Read this as a checklist for any tabs:

  • A name for the row. The APG asks for a label on the tab list. Lesson 10.1's exercise 6 built a label attribute, and the kit now has it.
  • A focus ring you can see. The APG asks that focus is always visible, and looks different from selection.
  • Hidden means hidden. The :host([hidden]) rule from lesson 10.1 stays.
  • Tabs that come and go. New tabs get set up, and the selection stays on a real tab.

The name comes from four lines at the top of #render():

Naming the tab row, from tea-tabs.jsJavaScript
const row = this.shadowRoot.querySelector(".tabs");
const label = this.getAttribute("label");
if (label === null) row.removeAttribute("aria-label");
else row.setAttribute("aria-label", label);

Line 2 reads the label attribute. Lines 3 and 4 copy it to the row's aria-label, or remove it. The row is in the shadow root, so the page can't point at it with an id. An attribute on the host can reach it.

The ring is one line of the template, line 11 of tea-tabs.js: ::slotted(:focus-visible) { outline: 2px solid seagreen; outline-offset: 2px; }. :focus-visible matches when the browser thinks a ring helps, mostly when someone uses the keyboard. Chrome shows no ring after a click on a tab. It shows the sea green ring after an arrow key moves focus. Focus is the ring, and selection is the bold text, so the two never look alike.

Tabs that come and go need no new code. The slotchange listener from lesson 10.1 runs #render() again, as lesson 8.4 taught. MDN notes that it fires when the slot's own nodes change. Try it:

Tabs added and removed laterPop out in the code editor (opens in a new tab)HTML
<tea-tabs label="Brewing guide" selected="2">  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <button slot="tab">Oolong</button>  <section slot="panel">Steep green tea for 2 minutes.</section>  <section slot="panel">Steep black tea for 4 minutes.</section>  <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs><button id="add">Add Puer</button><button id="remove">Remove the last tea</button> <script type="module">  import "./tea-tabs.js";  const tabs = document.querySelector("tea-tabs");  const all = (name) => [...tabs.querySelectorAll(`:scope > [slot="${name}"]`)];  document.querySelector("#add").addEventListener("click", () => {    tabs.insertAdjacentHTML("beforeend", '<button slot="tab">Puer</button><section slot="panel">Steep puer for 5 minutes.</section>');  });  document.querySelector("#remove").addEventListener("click", () => {    all("tab").at(-1)?.remove();    all("panel").at(-1)?.remove();  });  tabs.shadowRoot.querySelector('slot[name="tab"]').addEventListener("slotchange", () => {    console.log(all("tab").map((tab) => `${tab.textContent} ${tab.tabIndex}`).join(", "));  });</script>
ResultLoading…
  • Line 1 names the row Brewing guide and starts on Oolong.
  • Lines 16 to 18 add Puer: a tab and a panel. Lines 19 to 22 remove the last tab and the last panel.
  • Lines 23 to 25 print each tab and its tabindex after every slotchange. This listener runs after the component's own, which was added first.

At first, the console prints Green -1, Black -1, Oolong 0. Click Add Puer: Green -1, Black -1, Oolong 0, Puer -1. Puer is set up, and Oolong keeps the selection. Click Remove the last tea twice. The second click removes Oolong, the selected tab, and prints Green -1, Black 0. Black is the new last tab, so the getter picks it.

Chrome's accessibility tree shows the result. It has a tab list named Brewing guide, with two tabs, Green and Black. Black is selected, and the tab panel next to the list is named Black.

Three newer platform features also touch tabs:

  • Invoker Commands. A button anywhere on the page can send a command to an element, like <button commandfor="teas" command="--next">. The HTML Standard calls a name that starts with two dashes a custom command. For it, the browser only dispatches a command event on the target, so tea-tabs could listen and pick the next tab. Chrome 135, Firefox 144, and Safari 26.2 support it.
  • focusgroup. An attribute that gives a group arrow-key moves and one Tab stop, with no hand-written roving tabindex, as the Chrome 150 release notes describe. Only Chrome has it, from Chrome 150.
  • moveBefore(). If a page reorders tabs, lesson 3.5's moveBefore() keeps focus on a tab it moves. Chrome 133 and Firefox 144 have it. Safari doesn't.

Adding selection and events to the tea kit

The finished file is now tea-kit/tea-tabs.js in Ravi's kit. tea-kit/custom-elements.json, the kit's manifest from lesson 5.4, lists the label attribute, the tea-change event, and the TeaChangeEvent class. Here the tabs hold kit tea cards again, and the page hears two kinds of news:

Kit tabs and kit cards, with both eventsPop out in the code editor (opens in a new tab)HTML
<tea-tabs label="Teas">  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <button slot="tab">Oolong</button>  <section slot="panel"><tea-card name="Green tea" price="4"></tea-card></section>  <section slot="panel"><tea-card name="Black tea" price="3"></tea-card></section>  <section slot="panel"><tea-card name="Oolong" price="5"></tea-card></section></tea-tabs> <script type="module">  import { TeaChangeEvent } from "./tea-kit/tea-tabs.js";  import "./tea-kit/index.js";  document.addEventListener(TeaChangeEvent.type, (event) => {    console.log("Looking at", event.tab.textContent);  });  document.addEventListener("tea-add", (event) => {    console.log("Added", event.quantity, event.tea);  });</script>
ResultLoading…
  • Line 1 names the row Teas.
  • Line 11 imports TeaChangeEvent from the kit's file. Line 13 listens for its name, TeaChangeEvent.type.
  • Lines 16 to 18 listen for the card's tea-add, from lesson 9.2.

Click Black. The console prints Looking at Black. Press Add 1 on the Black tea card: Added 1 Black tea. Click the Black tab again, then press Right: Looking at Oolong. The card's button sits in a panel, not in the tab row, so the tabs never take a press on it for a pick.

Common mix-ups

  • "Every tab should be in the Tab order." No. Only the selected tab has tabindex="0". The arrow keys reach the others.
  • "Tabs should handle Up and Down too." No. Not in a row that runs across the page. Those keys keep scrolling it.
  • "Manual activation is always more accessible." No. The APG recommends automatic activation when panels show without delay.
  • "A setter and attributeChangedCallback() should each update the other." No. That's a loop. Let the setter write the attribute, and let the callback only draw.
  • "A number past the last tab should be written back into the attribute." No. The getter reads it as the last tab, as <progress> reads a value past max. The page's attribute stays as written.
  • "A property set before the class loads reaches the setter later." No. It hides the setter. #upgradeProperty() sends it through the setter.
  • "Setting selectedIndex should fire tea-change." No. The page made the change and already knows. Only clicks and keys send it.
  • "A name for each tag stops the nested leak." No. The same tag can sit inside itself. Check event.target.

Practice exercises

For each one, ask who made the change, a person or the page, and where the number lives.

Exercise 1 · Warm-upEnd, then Right

Click Green in the Result, then press End, then Right. What is the second line the console prints?

<tea-tabs>  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <button slot="tab">Oolong</button>  <section slot="panel">Steep green tea for 2 minutes.</section>  <section slot="panel">Steep black tea for 4 minutes.</section>  <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script type="module">  import "./tea-tabs.js";  document.querySelector("tea-tabs").addEventListener("tea-change", (event) => {    console.log("Picked", event.tab.textContent);  });</script>
ResultLoading…

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

    Exercise 2 · Warm-upA number past the last tab

    What does line 11 print?

    <tea-tabs selected="9">  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <section slot="panel">Steep green tea for 2 minutes.</section>  <section slot="panel">Steep black tea for 4 minutes.</section></tea-tabs> <script type="module">  import "./tea-tabs.js";  const tabs = document.querySelector("tea-tabs");  console.log(tabs.selectedIndex, tabs.getAttribute("selected"));</script>
    ResultLoading…

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

      Exercise 3 · PracticeFind the bug: an event for the page's own change

      Fix the tea-tabs.js tab, so the page's own change stays quiet. What does the fixed page print as it loads?

      <tea-tabs>  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <button slot="tab">Oolong</button>  <section slot="panel">Steep green tea for 2 minutes.</section>  <section slot="panel">Steep black tea for 4 minutes.</section>  <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script type="module">  import "./tea-tabs.js";  const tabs = document.querySelector("tea-tabs");  tabs.addEventListener("tea-change", (event) => console.log("tea-change:", event.tab.textContent));  tabs.selectedIndex = 2;  console.log("Ready");</script>
      ResultLoading…

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

        Exercise 4 · PracticeFind the bug: a value set too early

        Fix the tea-tabs.js tab, so the value from line 11 isn't lost. What does line 16 print now?

        <tea-tabs>  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <button slot="tab">Oolong</button>  <section slot="panel">Steep green tea for 2 minutes.</section>  <section slot="panel">Steep black tea for 4 minutes.</section>  <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script>  document.querySelector("tea-tabs").selectedIndex = 1;</script><script type="module">  import "./tea-tabs.js";  const tabs = document.querySelector("tea-tabs");  console.log("selected:", tabs.getAttribute("selected"));  console.log("Own property left:", Object.hasOwn(tabs, "selectedIndex"));</script>
        ResultLoading…

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

          Exercise 5 · ChallengeFind the bug: a callback that writes back

          Fix the class the way the kit does: the callback should never set the property. What does the fixed page print?

          <tea-tabs selected="1"></tea-tabs> <script>  let calls = 0;  class TeaTabs extends HTMLElement {    static observedAttributes = ["selected"];     get selectedIndex() {      return Number(this.getAttribute("selected"));    }     set selectedIndex(value) {      this.setAttribute("selected", value);    }     attributeChangedCallback(name, oldValue, newValue) {      calls++;      this.selectedIndex = Number(newValue);    }  }  customElements.define("tea-tabs", TeaTabs);  document.querySelector("tea-tabs").selectedIndex = 2;  console.log("Calls:", calls);</script>
          ResultLoading…

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

            Exercise 6 · ChallengeTabs in a column

            Make Down and Up work for <tea-tabs vertical>. Click Green, then press Down twice. What is the last line the console prints?

            <tea-tabs vertical>  <button slot="tab">Green</button>  <button slot="tab">Black</button>  <button slot="tab">Oolong</button>  <section slot="panel">Steep green tea for 2 minutes.</section>  <section slot="panel">Steep black tea for 4 minutes.</section>  <section slot="panel">Steep oolong for 3 minutes.</section></tea-tabs> <script type="module">  import "./tea-tabs.js";  document.querySelector("tea-tabs").addEventListener("tea-change", (event) => {    console.log("Picked", event.tab.textContent);  });</script>
            ResultLoading…

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

              Check your understanding

              For each question, ask who made the change and where the number lives.

              The tabs selection quiz · 8 questionsScore: first tries count
              1. Question 1 of 8In a horizontal row of tabs, what should Down Arrow do?

                Choose an answer to see the explanation.

              2. Question 2 of 8What does this page with three tabs print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <tea-tabs selected="5">
                  <button slot="tab">Green</button>
                  <button slot="tab">Black</button>
                  <button slot="tab">Oolong</button>
                  <section slot="panel">Steep green tea for 2 minutes.</section>
                  <section slot="panel">Steep black tea for 4 minutes.</section>
                  <section slot="panel">Steep oolong for 3 minutes.</section>
                </tea-tabs>
                
                <script type="module">
                  import "./tea-tabs.js";
                  const tabs = document.querySelector("tea-tabs");
                  console.log(tabs.selectedIndex, tabs.getAttribute("selected"));
                </script>

                Choose an answer to see the explanation.

              3. Question 3 of 8Black is selected and has focus. Where does the Tab key send focus next?

                Choose an answer to see the explanation.

              4. Question 4 of 8Why doesn't tabs.selectedIndex = 2 dispatch tea-change?

                Choose an answer to see the explanation.

              5. Question 5 of 8An outer tea-tabs listener prints Tea: Steep, from tabs inside Green's panel. Why?

                Choose an answer to see the explanation.

              6. Question 6 of 8Why does the kit's attributeChangedCallback() only call #render()?

                Choose an answer to see the explanation.

              7. Question 7 of 8When should tabs use manual activation instead of automatic?

                Choose an answer to see the explanation.

              8. Question 8 of 8A page sets selectedIndex = 2 before the kit loads, and the class has no #upgradeProperty(). What goes wrong?

                Choose an answer to see the explanation.

              Key takeaways

              • Listen for clicks and keys on the tab row in the shadow root, so the tabs hear only their own tabs.
              • Right and Left wrap, and Home and End jump. Up and Down stay free. Call preventDefault() only for the keys you handle.
              • Roving tabindex: 0 on the selected tab, -1 on the rest, and 0 on a panel that holds only text.
              • Pick automatic activation when panels show at once, and manual when they load slowly.
              • Keep the number in the attribute. The setter writes it, the getter reads it, and the callback only draws.
              • Read a bad value sensibly in the getter, and leave the page's attribute alone.
              • Run the upgrade-property pattern for selectedIndex.
              • Dispatch tea-change only for a click or a key, after the panel shows, and not for the tab already selected.
              • An outer listener checks event.target, so nested tabs can't fool it.

              Remember the one-liner.
              One place for the number, one door for a person's pick, and an event only when someone walks through it.

              Sources

              The facts on this page come from these standards, docs, and posts:

              Coming next: Debugging web components, the last lesson of module 10 in Shadow DOM, templates, and slots. It shows how to inspect shadow roots in DevTools, find an element's class, and pause in lifecycle callbacks.

              CompleteFrontend Clear concepts. Working examples.