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.
- 01Select 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. - 02Keep the attribute and the property in syncKeep the number in one place, so
selectedandselectedIndexalways agree, with no loop, sensible results for bad values, and no value lost before the upgrade. - 03Announce a person's pickDispatch
tea-changeonly 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:
<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>- 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.jstab. - Lines 12 to 14 listen for
tea-changeand 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.
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()settingselectedIndex - In real life: Calling your pick to the kitchen
- In JavaScript: Dispatching
tea-change
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:
- Managing selection: clicks, keys, and one Tab stop for the whole row.
- Keeping
selectedandselectedIndexin sync, even for bad or early values. - Sending
tea-changeat the right moments, even with tabs inside tabs. - 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:
#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 aspanaround 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:
/** 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 bycount. So with three tabs,3 % 3is 0: past the last tab, you land on the first. - Line 4 takes 1 away. Adding
countfirst 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
nullfor every other key, Down and Up included.
The keydown listener uses it:
#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:
#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);
}<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>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.
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:
| Question | Automatic activation | Manual 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:
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 owntabindex, 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.
<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>- 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.
focusinbubbles, 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.
tabindex. Green and Oolong have -1, so Tab skips them, and the arrow keys reach them instead.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:
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:
<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>- Lines 13 and 14 make a
MutationObserver, from lesson 8.4, that notes each write ofselected. - 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.
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.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
selectedattribute - 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().
<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>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.
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:
<progress max="3" value="7"></progress> <script> const progress = document.querySelector("progress"); console.log("value:", progress.value); console.log("attribute:", progress.getAttribute("value"));</script>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() { 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 ownselectedIndex, 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.
<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>- 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:
/** 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 adetailobject. - Line 3 keeps the name,
tea-change, in one place. A page can writeTeaChangeEvent.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.
<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>- 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.
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?
- 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
Sort each change by whether the tabs dispatch tea-change for it.
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:
<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>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.
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.
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.
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-changeevent - 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
labelattribute, 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():
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:
<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>- 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
tabindexafter everyslotchange. 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 acommandevent on the target, sotea-tabscould 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 rovingtabindex, as the Chrome 150 release notes describe. Only Chrome has it, from Chrome 150.moveBefore(). If a page reorders tabs, lesson 3.5'smoveBefore()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:
<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>- Line 1 names the row Teas.
- Line 11 imports
TeaChangeEventfrom 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 pastmax. 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.
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>Picked Green. End picks Oolong, so the first line is Picked Oolong. Right on the last tab wraps to the first, so keyTarget() gives (2 + 1) % 3, which is 0, and the second line is Picked Green.
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>1 9. With two tabs, the last position is 1, so selectedIndex gives 1, and Black shows. getAttribute() gives the page's own text, 9.
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><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>Ready. With the dispatch in #choose(), only clicks and keys send tea-change. The page's own selectedIndex = 2 stays quiet. A click on Black still prints tea-change: Black.
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><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>selected: 1. #upgradeProperty("selectedIndex") deletes the page's own property and sets it again, so the setter writes the attribute. Black shows, and clicks change the tab again.
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><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++; } } customElements.define("tea-tabs", TeaTabs); document.querySelector("tea-tabs").selectedIndex = 2; console.log("Calls:", calls);</script>Calls: 2. One call for the attribute in the HTML, during the upgrade, and one for line 22. Lesson 3.4's guard, if (oldValue === newValue) return;, would also stop the loop, but it prints Calls: 4: each change still writes twice.
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><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>Picked Oolong. The solution's tea-tabs.js tab maps Down to Right and Up to Left only when the host has vertical, so the first Down picks Black and the second picks Oolong. It also sets aria-orientation, so screen readers know which keys to use.
Check your understanding
For each question, ask who made the change and where the number lives.
Question 1 of 8In a horizontal row of tabs, what should Down Arrow do?
Choose an answer to see the explanation.
Question 2 of 8What does this page with three tabs print?
Read the code, then predict<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.
Question 3 of 8Black is selected and has focus. Where does the Tab key send focus next?
Choose an answer to see the explanation.
Question 4 of 8Why doesn't
tabs.selectedIndex = 2dispatchtea-change?Choose an answer to see the explanation.
Question 5 of 8An outer
tea-tabslistener printsTea: Steep, from tabs inside Green's panel. Why?Choose an answer to see the explanation.
Question 6 of 8Why does the kit's
attributeChangedCallback()only call#render()?Choose an answer to see the explanation.
Question 7 of 8When should tabs use manual activation instead of automatic?
Choose an answer to see the explanation.
Question 8 of 8A page sets
selectedIndex = 2before 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-changeonly 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:
- WAI-ARIA APG: Tabs pattern, keyboard interaction, W3C.
- WAI-ARIA APG: Developing a keyboard interface, W3C.
- Enter, it screams... I mean, it streams, Westbrook Johnson.
- Custom element best practices, web.dev.
- Attribute reflection: Reflected attributes, MDN.
- Using custom elements: Responding to attribute changes, MDN.
- HTML Standard: The progress element, WHATWG.
- Handling properties in custom element upgrades, Nolan Lawson.
- Lit docs: When to dispatch an event, Lit.
- Lit docs: Dispatching events after an element updates, Lit.
- Stop Using CustomEvent, Justin Fagnani.
- Custom Event Names and the Bubbling Problem, Cory LaViska.
- HTMLSlotElement: slotchange event, MDN.
- :focus-visible, MDN.
- HTML Standard: The button element's command attribute, WHATWG.
- Chrome 150 release notes: Focusgroup, Chrome for Developers.
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.