Build a switch
Build a toggle switch web component that sends its value with a form, resets to its checked attribute, checks required, and works with Space, Enter, and ARIA.
- 01Make a switch a form controlSend its value only while it's on, check
required, and keep thecheckedattribute as the start a reset goes back to. - 02Make it work for everyoneFlip it with a click, a label, Space, and Enter, once per press, and give screen readers its role and state through its internals.
- 03Style its statesStyle on and off with
:state(checked), and handle disabled, forced colors, right to left, and reduced motion.
How do you build a toggle switch web component?
It's Saturday at Leaf and Kettle. Meena adds one choice to the online order form: Add oat milk. She uses the kit's switch, tea-toggle, from lesson 13.2. It looks right. Its thumb moves over, it turns green, and screen readers call it a switch.
Asha orders a Sencha and turns oat milk on. The kitchen gets Sencha, with no oat milk. Then she presses Clear order. The tea goes back to Sencha, but the switch stays on. Why does a switch that looks finished do so little?
A toggle switch web component is a form-associated custom element. Its host takes focus, has the role switch, flips on a click, Space, or Enter, and hands its form a value only while it's on. Its checked attribute is where it starts, and a reset puts it back there. The kit's switch does the first part. The form never hears about it.
Here is Meena's form. Try what Asha tried:
<link rel="stylesheet" href="tea-kit/tokens.css"><form id="order"> <p><label>Tea <select name="tea"><option>Sencha</option><option>Assam</option></select></label></p> <p><tea-toggle name="oat">Add oat milk</tea-toggle></p> <button>Order</button> <button type="reset">Clear order</button></form><script type="module"> import "./tea-kit/index.js"; const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script>- Line 3 is the tea. Line 4 is the kit's switch, with the name oat.
- Lines 5 and 6 are Order and Clear order. Clear order is a reset button.
- Lines 11 to 14 stop the real send, which would load a new page in the Result. They print what the form would send.
Click Add oat milk, then Order. It prints Sent: tea=Sencha. Press Clear order. The switch stays on.
Ravi puts a new light switch in the tea room. It clicks up and down, and it looks just like the others. But nobody ran a wire from it to the fuse box. So the lamp never lights, however often you flip it.
- In real life: The switch on the wall
- In JavaScript:
tea-toggleon the page - In real life: The wire to the fuse box
- In JavaScript:
formAssociatedandsetFormValue() - In real life: The fuse box
- In JavaScript: The form
- In real life: A lamp that never lights
- In JavaScript: A switch the form never hears
A switch is a checkbox with a different look. Build it as a form control. It sends a value only while it's on. Its checked attribute is where it starts. And every flip tells the form, the screen reader, and your CSS.
This lesson finishes the switch, piece by piece. Each piece is something module 16 taught, so each one links back. The switch is a form-associated custom element, from lesson 16.1. Those work in Chrome 77, Firefox 98, and Safari 16.4 and later.
Is there a native HTML switch element?
Yes, in one browser. The HTML Standard gives <input type="checkbox"> a switch attribute. With it, the checkbox is drawn as a switch with two states, on and off. Safari draws it from Safari 17.4. Chrome and Firefox don't have it yet. Run this in your browser:
<label><input type="checkbox" switch name="oat"> Add oat milk</label><script> const box = document.querySelector("input"); console.log("Knows switch:", "switch" in box);</script>- Line 1 is a checkbox with the switch attribute, inside its label.
- Line 4 asks whether the input knows the attribute. Chrome prints
Knows switch: false. Safari printsKnows switch: true.
Chrome shows a plain checkbox, and its accessibility tree says so:
checkbox "Add oat milk", checked: falseThat's still useful. WebKit's team designed it so a browser without the attribute shows a checkbox. The form gets the same value either way. The APG has an example that styles a real checkbox as a switch, with role="switch". Wrapping that in a component is the wrapper design from lesson 16.5.
This lesson builds the switch from scratch instead, with the host as the control. That shows every part a native control gives you for free. When Chrome and Firefox ship the attribute, you'll know what it does.
Why it matters: check for a native control first. A switch is the rare case where one exists, but not everywhere yet.
How do you scaffold a form-associated switch?
Start from the smallest switch that works in a form. It's the switch from lesson 13.2, joined to its form. The class is in the tea-toggle.js tab:
<form id="order"> <tea-toggle name="oat">Add oat milk</tea-toggle> <button>Order</button></form><script src="tea-toggle.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script>class TeaToggle extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
constructor() {
super();
this.#internals.role = "switch";
this.#internals.ariaChecked = "false";
this.attachShadow({ mode: "open" }).innerHTML = `<style>
:host { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; }
.track { inline-size: 36px; block-size: 20px; padding: 2px; border-radius: 10px; background: dimgray; }
.thumb { display: block; inline-size: 16px; block-size: 16px; border-radius: 50%; background: white; }
:host(:state(checked)) .track { background: seagreen; }
:host(:state(checked)) .thumb { margin-inline-start: 16px; }
:host(:disabled) { cursor: default; opacity: 0.5; }
</style>
<span class="track"><span class="thumb"></span></span><slot></slot>`;
this.addEventListener("click", () => this.#flip());
}
connectedCallback() {
if (!this.hasAttribute("tabindex")) this.tabIndex = 0;
}
#flip() {
const on = !this.#internals.states.has("checked");
if (on) this.#internals.states.add("checked");
else this.#internals.states.delete("checked");
this.#internals.ariaChecked = String(on);
this.#internals.setFormValue(on ? "on" : null);
}
}
customElements.define("tea-toggle", TeaToggle);- Line 2 makes it form-associated, and line 3 asks for its internals, as in lesson 16.1.
- Lines 7 and 8 give the host its role and state, through the internals (lesson 13.2).
- Lines 9 to 17 draw a track and a round thumb, with the label in a slot.
- Line 18 flips it on every click. Line 22 puts it in the Tab order, unless the page wrote a tabindex (lesson 14.1).
- Lines 25 to 31 are
#flip(). Line 26 works out the new position. Lines 27 and 28 set the checked state. Line 29 setsariaChecked. Line 30 hands the form"on", ornull.
Press Order: Sent: nothing. Click the switch, then Order: Sent: oat=on. Chrome's tree now reads:
switch "Add oat milk", checked: trueThis is close to the HTML Standard's own example, a checkbox that sends "on" or nothing. Each flip has three audiences, and #flip() tells all three:
#flip(), and #flip() tells three audiences at once. Leave one call out, and that audience never hears about the flip.Why it matters: none of the three reads the others. If one call is missing, the switch looks on but sends nothing, or sends on but reads as off.
What does a switch send with its form?
The same as a checkbox. When the form is sent, the browser makes a list of entries, one per control with a name. The HTML Standard skips a checkbox that isn't checked. A checked one sends its value, and its value is "on" unless the page wrote value.
Ravi writes the extras on each order slip, one line per extra the customer wants. Nobody writes "no honey". If there's no honey line, the kitchen adds no honey.
- In real life: A line on the slip
- In JavaScript: An entry in
FormData - In real life: The extra's name
- In JavaScript: The
nameattribute - In real life: What Ravi writes, like honey
- In JavaScript: The
value, or"on" - In real life: No line at all
- In JavaScript: A switch that's off
Here is a native checkbox beside two switches. The second switch has value="honey". In the tab, only line 30 changed, and lines 33 to 35 are new:
<form id="order"> <label><input type="checkbox" name="lemon"> Lemon</label> <tea-toggle name="milk">Add milk</tea-toggle> <tea-toggle name="extra" value="honey">Add honey</tea-toggle> <button>Order</button></form><script src="tea-toggle.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); const data = new FormData(form); console.log("Sent:", new URLSearchParams(data).toString() || "nothing"); console.log("milk:", data.get("milk")); });</script>class TeaToggle extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
constructor() {
super();
this.#internals.role = "switch";
this.#internals.ariaChecked = "false";
this.attachShadow({ mode: "open" }).innerHTML = `<style>
:host { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; }
.track { inline-size: 36px; block-size: 20px; padding: 2px; border-radius: 10px; background: dimgray; }
.thumb { display: block; inline-size: 16px; block-size: 16px; border-radius: 50%; background: white; }
:host(:state(checked)) .track { background: seagreen; }
:host(:state(checked)) .thumb { margin-inline-start: 16px; }
:host(:disabled) { cursor: default; opacity: 0.5; }
</style>
<span class="track"><span class="thumb"></span></span><slot></slot>`;
this.addEventListener("click", () => this.#flip());
}
connectedCallback() {
if (!this.hasAttribute("tabindex")) this.tabIndex = 0;
}
#flip() {
const on = !this.#internals.states.has("checked");
if (on) this.#internals.states.add("checked");
else this.#internals.states.delete("checked");
this.#internals.ariaChecked = String(on);
this.#internals.setFormValue(on ? this.value : null);
}
get value() {
return this.getAttribute("value") ?? "on";
}
}
customElements.define("tea-toggle", TeaToggle);- On the page, line 2 is the native checkbox. Lines 3 and 4 are the switches.
- Line 13 prints every entry. Line 14 asks
FormDataformilkby name (FormData, in the JavaScript path). - In the tab, lines 33 to 35 read the value attribute, or give
"on". - Line 30 hands the form that value while the switch is on, and
nullwhile it's off.
- Press Order. It prints
Sent: nothingandmilk: null. An off control sends nothing. - Tick Lemon, turn both switches on, and press Order. It prints
Sent: lemon=on&milk=on&extra=honeyandmilk: on.
null means "no entry", as lesson 16.2 showed. Without a name, nothing is sent at all (lesson 16.1).
A switch that must be on
Some switches must be on before the form can go, like I read the allergy notice. A native checkbox with required is missing its value while it's unticked. Your class says the same with setValidity(), as in lesson 16.3:
<form id="order"> <tea-toggle name="notice" required>I read the allergy notice</tea-toggle> <button>Order</button></form><script src="tea-toggle.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("invalid", (event) => console.log("Not sent:", event.target.textContent), true); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script>class TeaToggle extends HTMLElement {
static formAssociated = true;
static observedAttributes = ["required"];
#internals = this.attachInternals();
constructor() {
super();
this.#internals.role = "switch";
this.#internals.ariaChecked = "false";
this.attachShadow({ mode: "open" }).innerHTML = `<style>
:host { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; }
.track { inline-size: 36px; block-size: 20px; padding: 2px; border-radius: 10px; background: dimgray; }
.thumb { display: block; inline-size: 16px; block-size: 16px; border-radius: 50%; background: white; }
:host(:state(checked)) .track { background: seagreen; }
:host(:state(checked)) .thumb { margin-inline-start: 16px; }
:host(:disabled) { cursor: default; opacity: 0.5; }
</style>
<span class="track"><span class="thumb"></span></span><slot></slot>`;
this.addEventListener("click", () => this.#flip());
}
connectedCallback() {
if (!this.hasAttribute("tabindex")) this.tabIndex = 0;
}
attributeChangedCallback() {
this.#internals.ariaRequired = String(this.hasAttribute("required"));
this.#show(this.#internals.states.has("checked"));
}
#flip() {
this.#show(!this.#internals.states.has("checked"));
}
#show(on) {
if (on) this.#internals.states.add("checked");
else this.#internals.states.delete("checked");
this.#internals.ariaChecked = String(on);
this.#internals.setFormValue(on ? this.value : null);
if (on || !this.hasAttribute("required")) this.#internals.setValidity({});
else this.#internals.setValidity({ valueMissing: true }, "Please turn this switch on.");
}
get value() {
return this.getAttribute("value") ?? "on";
}
}
customElements.define("tea-toggle", TeaToggle);- Line 3 of the tab watches
required. Lines 26 to 29 run when it changes. - Line 27 sets
ariaRequired. The ARIA section says why the browser needs it. - Line 32: every flip now goes through
#show(), on lines 35 to 42. One method for every change keeps everything in step, as in lesson 16.4. - Lines 40 and 41 set the validity. While it's required and off, the flag is
valueMissing, with the message "Please turn this switch on." - On the page, line 8 prints each control that stops the form.
Press Order. Chrome shows "Please turn this switch on." at the switch, and prints Not sent: I read the allergy notice. Turn it on and press Order: Sent: notice=on.
Why it matters: a form only sends what its controls hand it. The switch decides what it hands over, and when.
Should the checked attribute change when you flip a switch?
No. On a checkbox, the checked attribute and the checked property are two different things. Click Lemon, then press Clear order:
<form> <label><input type="checkbox" name="lemon" checked> Lemon</label> <button type="reset">Clear order</button></form><script> const lemon = document.querySelector("input"); const show = () => console.log(`checked: ${lemon.checked}, defaultChecked: ${lemon.defaultChecked}`); lemon.addEventListener("change", show); document.querySelector("form").addEventListener("reset", () => setTimeout(show));</script>- Line 2 is a checkbox that starts ticked, with the
checkedattribute. - Line 7 prints two properties.
checkedis where it is now.defaultCheckedreads thecheckedattribute. - Line 8 prints after each click. Line 9 prints after a reset. It waits a moment, because the
resetevent fires before the controls reset (lesson 16.4).
The click prints checked: false, defaultChecked: true. Clear order prints checked: true, defaultChecked: true.
The click moved the property, and the attribute stayed. Lesson 5.1 showed this split: checked reflects nothing, and defaultChecked reflects the attribute. The HTML Standard calls the attribute the default, and a reset copies it back into the property. Jake Archibald shows the same split for an input's value.
Each hotel room has a housekeeping card: lamp on. The guest flips the lamp off and on as they like. If the card is changed during the stay, nobody walks in to move the switch. At checkout, housekeeping sets the lamp to what the card says.
- In real life: The card: lamp on
- In JavaScript: The
checkedattribute - In real life: Where the guest left the switch
- In JavaScript: The
checkedproperty - In real life: Checkout, when housekeeping sets it from the card
- In JavaScript:
formResetCallback() - In real life: A guest who has touched the switch
- In JavaScript: The dirty flag: the attribute stops leading
Now the switch. Here are three ways to write it. Click Add milk to turn it off, press Clear order, then press Order:
<form id="order"> <tea-toggle name="milk" checked>Add milk</tea-toggle> <button>Order</button> <button type="reset">Clear order</button></form><script src="tea-toggle.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script>The click removed the checked attribute. So the reset reads the attribute, finds none, and leaves the switch off. It prints Sent: nothing.
The three tabs answer the same two questions in different ways:
- Write the attribute. The
checkedproperty adds and removes the attribute, as the HTML Standard's example does. A click erases the start, so the reset has nothing to go back to. - Reset to off. The position lives in the internals, but the reset turns it off. That ignores the
checkedthe page wrote. - Keep the attribute as the start. The click moves only the property, and the reset reads the attribute.
checked attribute says where the switch starts, and a click never moves it. The property says where it is now. Clear order copies the attribute into the property.Here is the third tab, the one that works like a checkbox:
class TeaToggle extends HTMLElement {
static formAssociated = true;
static observedAttributes = ["checked"];
#internals = this.attachInternals();
#dirty = false;
constructor() {
super();
this.#internals.role = "switch";
this.#internals.ariaChecked = "false";
this.attachShadow({ mode: "open" }).innerHTML = `<style>
:host { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; }
.track { inline-size: 36px; block-size: 20px; padding: 2px; border-radius: 10px; background: dimgray; }
.thumb { display: block; inline-size: 16px; block-size: 16px; border-radius: 50%; background: white; }
:host(:state(checked)) .track { background: seagreen; }
:host(:state(checked)) .thumb { margin-inline-start: 16px; }
:host(:disabled) { cursor: default; opacity: 0.5; }
</style>
<span class="track"><span class="thumb"></span></span><slot></slot>`;
this.addEventListener("click", () => {
this.checked = !this.checked;
});
}
connectedCallback() {
if (!this.hasAttribute("tabindex")) this.tabIndex = 0;
}
attributeChangedCallback() {
if (!this.#dirty) this.#show(this.defaultChecked);
}
formResetCallback() {
this.#dirty = false;
this.#show(this.defaultChecked);
}
get checked() {
return this.#internals.states.has("checked");
}
set checked(value) {
this.#dirty = true;
this.#show(Boolean(value));
}
get defaultChecked() {
return this.hasAttribute("checked");
}
#show(on) {
if (on) this.#internals.states.add("checked");
else this.#internals.states.delete("checked");
this.#internals.ariaChecked = String(on);
this.#internals.setFormValue(on ? "on" : null);
}
}
customElements.define("tea-toggle", TeaToggle);- Line 5 is the dirty flag: has someone moved the switch? The HTML Standard calls it dirty checkedness.
- Lines 29 to 31 let the attribute move the switch only while nobody has. Lines 42 to 45 are the setter: a click or a script sets the flag, then moves the switch.
- Lines 33 to 36 are the reset. Line 34 clears the flag, and line 35 goes back to the attribute.
- Lines 47 to 49 are
defaultChecked, which reads the attribute, as on a checkbox.
Web Awesome's switch works the same way. Its defaultChecked is the checked attribute, and its reset clears the current position.
Why it matters: the page's HTML says where a switch starts. Only a person, a script, or a reset should move it.
How does a switch handle reset and the Back button?
Two form callbacks from lesson 16.4 bring a switch back, in two different ways:
formResetCallback()runs on a reset. It goes back to thecheckedattribute, as you just saw.formStateRestoreCallback(state)runs after Back, when the browser loads the page again. It brings back where the person left the switch.
Here is the finished switch. It has everything so far, plus the keys and events of the next section. Turn Add milk off and Add oat milk on, then press Order. Then press Clear order, and Order again:
<form id="order"> <p><tea-toggle name="milk" checked>Add milk</tea-toggle></p> <p><tea-toggle name="oat">Add oat milk</tea-toggle></p> <button>Order</button> <button type="reset">Clear order</button></form><script src="tea-toggle.js"></script><script> const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script>class TeaToggle extends HTMLElement {
static formAssociated = true;
static observedAttributes = ["checked", "value", "required"];
#internals = this.attachInternals();
#dirty = false;
constructor() {
super();
this.#internals.role = "switch";
this.#internals.ariaChecked = "false";
this.attachShadow({ mode: "open" }).innerHTML = `<style>
:host { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; }
.track { inline-size: 36px; block-size: 20px; padding: 2px; border-radius: 10px; background: dimgray; }
.thumb { display: block; inline-size: 16px; block-size: 16px; border-radius: 50%; background: white; }
:host(:state(checked)) .track { background: seagreen; }
:host(:state(checked)) .thumb { margin-inline-start: 16px; }
:host(:disabled) { cursor: default; opacity: 0.5; }
</style>
<span class="track"><span class="thumb"></span></span><slot></slot>`;
this.addEventListener("click", () => this.#flip());
this.addEventListener("keydown", (event) => {
if (event.key !== " " && event.key !== "Enter") return;
event.preventDefault();
if (event.key === "Enter" && !event.repeat) this.click();
});
this.addEventListener("keyup", (event) => {
if (event.key === " ") this.click();
});
}
connectedCallback() {
if (!this.hasAttribute("tabindex")) this.tabIndex = 0;
}
attributeChangedCallback(name) {
if (name === "required") this.#internals.ariaRequired = String(this.hasAttribute("required"));
if (name === "checked" && !this.#dirty) this.#show(this.defaultChecked);
else this.#show(this.checked);
}
formResetCallback() {
this.#dirty = false;
this.#show(this.defaultChecked);
}
formStateRestoreCallback(state) {
this.checked = state === "on";
}
#flip() {
this.checked = !this.checked;
this.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
this.dispatchEvent(new Event("change", { bubbles: true }));
}
#show(on) {
if (on) this.#internals.states.add("checked");
else this.#internals.states.delete("checked");
this.#internals.ariaChecked = String(on);
this.#internals.setFormValue(on ? this.value : null, on ? "on" : "off");
if (on || !this.hasAttribute("required")) this.#internals.setValidity({});
else this.#internals.setValidity({ valueMissing: true }, "Please turn this switch on.");
}
get checked() {
return this.#internals.states.has("checked");
}
set checked(value) {
this.#dirty = true;
this.#show(Boolean(value));
}
get defaultChecked() {
return this.hasAttribute("checked");
}
get value() {
return this.getAttribute("value") ?? "on";
}
}
customElements.define("tea-toggle", TeaToggle);The first Order prints Sent: oat=on. After Clear order, it prints Sent: milk=on. Add milk went back on, because the page wrote checked.
Now the Back button. A restore hands back the state you passed to setFormValue() (lesson 16.2). Look at line 60 of the tab. While on, it saves "on". While off, the value is null, but the state is "off". Lines 46 to 48 turn that state back into a position.
Why save a state for off? The Result can't press Back, so the course's test ran this page on a real address. It turned Add milk off and Add oat milk on, followed a link, pressed Back, and pressed Order. It ran once with line 60 as setFormValue(on ? this.value : null), and once as it is:
Without a state: Sent: milk=on&oat=on
With a state: Sent: oat=onWithout a state, Add milk had saved nothing, so Chrome had nothing to hand back. The switch started from its attribute: on. It's like a coat check with no ticket. With the state, the callback got "off", and Add milk stayed off.
"off" saved, the callback gets it, and the switch stays off.When Chrome keeps the whole page in its back/forward cache, Back shows it as it was, and nothing needs restoring (lesson 16.4).
A disabled switch
What about formDisabledCallback()? Lesson 16.4 used it to turn off the controls inside a shadow root. This switch has none. The host is the control, and the browser already keeps a disabled host out of reach. Tick This is a gift to open the gift section:
<form id="order"> <p><tea-toggle name="milk">Add milk</tea-toggle></p> <fieldset id="gift" disabled> <legend><label><input type="checkbox" id="is-gift"> This is a gift</label></legend> <tea-toggle name="wrap">Gift wrap</tea-toggle> </fieldset> <button>Order</button></form><script src="tea-toggle.js"></script><script> const form = document.querySelector("#order"); document.querySelector("#is-gift").addEventListener("change", (event) => { document.querySelector("#gift").disabled = !event.target.checked; }); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script>- Line 3 is the gift fieldset, disabled from the start. Line 4 is its legend, with the tick box.
- Line 5 is Gift wrap, the finished switch. Lines 12 to 14 open and close the fieldset.
- Click Gift wrap. Nothing happens: Chrome sends no click to a disabled form control. Press Order:
Sent: nothing. - Click Add milk twice, then press Tab. Focus goes to This is a gift, and the next Tab skips Gift wrap.
- Tick This is a gift, click Gift wrap, and press Order:
Sent: wrap=on.
Its tag still says tabindex="0", yet focus skips it. The class writes no disabled code at all. The host matches :disabled, and line 17 of the tab greys it out.
Why it matters: reset and Back are how a form comes back. A switch that ignores them is the one choice that comes back wrong.
Which keys should toggle a switch?
The APG's switch pattern says Space flips a switch, and Enter may flip it too. When matters as much as which. Hold a key down, and the keyboard sends keydown again and again, then one keyup when you let go. Westbrook Johnson shows how a button handles it: Space clicks on keyup, and Enter clicks on keydown, so a held Enter clicks again and again.
Asha holds the lift's call button for a few seconds. The lift comes once. It doesn't come, leave, and come back for every second she held it.
- In real life: Holding the button down
- In JavaScript: Holding Space or Enter
- In real life: The button's signal, over and over
- In JavaScript: Repeated
keydownevents - In real life: The lift is called once
- In JavaScript: The switch flips once
- In real life: Letting go
- In JavaScript:
keyup
Try both sets of keys. Click Your order, then press Tab to reach the switch. Hold Space down for a second, and let go. Then hold Enter down, and let go:
<p>Your order</p><tea-toggle name="milk">Add milk</tea-toggle><script src="tea-toggle.js"></script><script> const milk = document.querySelector("tea-toggle"); milk.addEventListener("change", () => console.log("change:", milk.checked ? "on" : "off"));</script>Every keydown flips it, and a held key sends keydown many times a second. The test sent three keydowns, so it printed on, off, on. Enter does nothing.
The second tab is the finished file. In its tea-toggle.js tab:
- Line 22 lets only Space and Enter through.
- Line 23 stops the page scrolling, which Space does on its own.
- Line 24 flips the switch on Enter's first
keydown.event.repeatistruefor the repeats (MDN), so they're skipped. - Lines 26 to 28 flip it on Space's
keyup, once.
keydown again and again, then one keyup. Space flips the switch on the keyup. Enter flips it on the first keydown, and the repeats are skipped.Chrome's own settings switch, cr-toggle, uses the same keys in the same way. A native checkbox flips on Space's keyup too. Enter is different there: in a form, Enter on a checkbox sends the form. The APG lets a switch use Enter to flip instead, and the kit does. For more on keydown and keyup, see keydown and keyup in the JavaScript path.
Clicks, labels, and the events the page hears
Both keys call this.click(), so every flip goes through the click listener on line 20. A label's click reaches the switch too, as lesson 13.4 showed. Click the words Add milk:
<form id="order"> <label for="milk">Add milk</label> <tea-toggle id="milk" name="milk"></tea-toggle></form><script src="tea-toggle.js"></script><script> const form = document.querySelector("#order"); const milk = document.querySelector("#milk"); form.addEventListener("input", () => console.log("input:", milk.checked)); form.addEventListener("change", () => console.log("change:", milk.checked)); milk.checked = true; console.log("A script set it:", milk.checked);</script>- Line 2 is a label for the switch on line 3.
- Lines 9 and 10 print each
inputandchangethe form hears. - Line 11 turns the switch on from a script, and line 12 prints it.
When the page opens, it prints only A script set it: true. Click Add milk: input: false, then change: false.
A checkbox works the same way. A person's flip fires input, then change, and a script setting checked fires nothing. In the finished file, lines 52 and 53 fire both from #flip(), never from the setter. input is composed and change isn't, as on a checkbox (lesson 9.2).
Why it matters: keyboard users hold keys, and pages listen for change. One flip per press keeps both right.
What ARIA does a custom switch need?
The APG lists two things: the role switch, and aria-checked set to true or false. It also says the label must not change with the state. The words stay Add milk, and only checked changes. Here are three switches, on, required, and disabled:
<form> <p><tea-toggle name="milk" checked>Add milk</tea-toggle></p> <p><tea-toggle name="notice" required>I read the allergy notice</tea-toggle></p> <p><tea-toggle name="wrap" disabled>Gift wrap</tea-toggle></p></form><script src="tea-toggle.js"></script><script> for (const toggle of document.querySelectorAll("tea-toggle")) { console.log(toggle.outerHTML.slice(0, toggle.outerHTML.indexOf(">") + 1)); }</script>switch "Add milk", checked: true
switch "I read the allergy notice", checked: false, invalid: true
switch "Gift wrap", checked: false, disabled: true- Lines 2 to 4 are the switches. Lines 8 to 10 print each tag as the page sees it.
- The tags print with no
roleand noaria-checked. They only gettabindex="0". - The tree still gives each one its role and state, from the internals.
Lines 9 and 10 of the finished file set those defaults. A role the page writes on the tag still wins (lesson 13.2). Two more lines are worth a look:
- Required needs ARIA. Chrome reads required from a native control's own attribute. For anything else, it reads only
aria-required, in AXNodeObject::IsRequired(). A custom element isn't a native control, so line 36 setsariaRequired. - Disabled doesn't. The switch never sets
ariaDisabled, yet the tree saysdisabled: true. The browser knows a form-associated element is disabled. SaveariaDisabledfor a part that looks off but stays focusable, like lesson 16.4's readonly buttons. - Invalid comes free. I read the allergy notice is required and off, so its row says
invalid: true, from the validity alone.
Before you ship it, run lesson 15.3's axe check, and listen to it with a screen reader.
Why it matters: a screen reader user can only flip what they know is a switch, and know it's on.
How do you style a switch with :state(checked)?
Style where the switch is now, not where it started. That rules out the checked attribute. The class adds the checked state on every flip, and CSS matches it with :state(checked) (lesson 12.3).
The shop's kettle has a little light that comes on with its switch. Nobody paints it. A sticker saying ON would still say ON after Ravi switched the kettle off.
- In real life: The kettle's little light
- In JavaScript:
:state(checked) - In real life: It comes on by itself
- In JavaScript: The class adds the state on every flip
- In real life: A sticker that says ON
- In JavaScript: A rule on
[checked]
A page can style the switch from outside, too. Try both rules. Click Add milk twice:
<style> tea-toggle[checked] { font-weight: bold; }</style><tea-toggle name="milk" checked>Add milk</tea-toggle><script src="tea-toggle.js"></script><script> const milk = document.querySelector("tea-toggle"); milk.addEventListener("change", () => { const bold = getComputedStyle(milk).fontWeight === "700"; console.log(`${milk.checked ? "On" : "Off"}, bold: ${bold ? "yes" : "no"}`); });</script>The checked attribute doesn't move when you click, so the words stay bold while the switch is off. It prints Off, bold: yes, then On, bold: yes.
- Line 2 is the page's rule. Line 4 is a switch that starts on.
- Lines 8 to 11 print, after each change, whether the words are bold.
With [checked], the switch turns off and stays bold. With :state(checked), the words are bold only while it's on. A custom element never matches :checked, which is only for native controls. Chrome 90 to 124 spelled the state :--checked; use :state() (lesson 12.3). Cory LaViska sums up the usual view: attributes are the page's input, so a component shouldn't add its own to show its state. Custom states give it another way.
Here are the kit's switch styles, from tea-kit/tea-toggle.js:
@layer component {
:host { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; border-radius: 4px; }
.track { display: inline-block; inline-size: 36px; block-size: 20px; padding: 2px; border-radius: 10px; background: var(--tea-color-stone, dimgray); }
.thumb { display: block; inline-size: 16px; block-size: 16px; border-radius: 50%; background: var(--tea-color-paper, white); transition: margin-inline-start calc(var(--tea-motion, 1) * 150ms); }
}
@layer state {
:host(:focus-visible) { outline: 2px solid var(--tea-focus-ring, var(--tea-color-leaf, seagreen)); outline-offset: 2px; }
:host(:state(checked)) .track { background: var(--tea-color-leaf, seagreen); }
:host(:state(checked)) .thumb { margin-inline-start: 16px; }
:host(:disabled) { cursor: default; opacity: 0.5; }
@media (forced-colors: active) {
.track { border: 1px solid CanvasText; padding: 1px; }
.thumb { background: CanvasText; }
:host(:state(checked)) .track { background: Highlight; }
:host(:state(checked)) .thumb { background: HighlightText; }
:host(:disabled) { opacity: 1; }
:host(:disabled) .track { border-color: GrayText; background: Canvas; }
:host(:disabled) .thumb { background: GrayText; }
}
}- Lines 8 and 9 draw the on position with
:state(checked). Line 9 moves the thumb withmargin-inline-start, so it slides left on a right-to-left page (lesson 15.2). - Line 4 slides the thumb for 150ms times
--tea-motion. The kit sets--tea-motion: 0when the person asks for reduced motion, so the thumb jumps (lesson 12.7). - Line 10 greys out a disabled switch, and line 7 draws the focus ring.
- Lines 11 to 19 use system colors in forced colors mode (lesson 15.1). Lines 16 to 18 are new: a disabled switch turns
GrayText, the system color for disabled text.
Why it matters: :state() styles the position a person sees and a screen reader hears, from one source of truth. MDN has the full syntax.
Finishing the kit's switch
Back to Meena's form. The kit's new version, kitAfter171, makes tea-toggle the finished switch. Here is the order form with three of them:
<link rel="stylesheet" href="tea-kit/tokens.css"><form id="order"> <p><tea-toggle name="milk" checked>Add milk</tea-toggle></p> <p><tea-toggle name="extra" value="honey">Add honey</tea-toggle></p> <p><tea-toggle name="notice" required>I read the allergy notice</tea-toggle></p> <button>Order</button> <button type="reset">Clear order</button></form><script type="module"> import "./tea-kit/index.js"; const form = document.querySelector("#order"); form.addEventListener("change", (event) => console.log(`${event.target.name}: ${event.target.checked ? "on" : "off"}`)); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString() || "nothing"); });</script>- Line 3 starts on. Line 4 sends honey. Line 5 is required.
- Line 12 prints each change the form hears, with the switch's name.
- Press Order. Chrome shows "Please turn this switch on." at the notice switch, and nothing prints.
- Click I read the allergy notice:
notice: on. Press Shift and Tab to go back to Add honey, and press Space:extra: on. - Press Order:
Sent: milk=on&extra=honey¬ice=on. Press Clear order. Add milk stays on, and the others turn off.
Here is the class, from tea-kit/tea-toggle.js:
export class TeaToggle extends HTMLElement {
static formAssociated = true;
static observedAttributes = ["checked", "value", "required"];
#internals = attachInternals(this);
#dirty = false;
constructor() {
super();
this.#internals.role = "switch";
this.#internals.ariaChecked = "false";
this.attachShadow({ mode: "open" });
this.shadowRoot.adoptedStyleSheets = [base, sheet];
this.shadowRoot.append(template.content.cloneNode(true));
this.addEventListener("click", () => this.#flip());
this.addEventListener("keydown", (event) => {
if (event.key !== " " && event.key !== "Enter") return;
event.preventDefault();
if (event.key === "Enter" && !event.repeat) this.click();
});
this.addEventListener("keyup", (event) => {
if (event.key === " ") this.click();
});
}
connectedCallback() {
if (!this.hasAttribute("tabindex")) this.tabIndex = 0;
}
attributeChangedCallback(name) {
if (name === "required") this.#internals.ariaRequired = String(this.hasAttribute("required"));
if (name === "checked" && !this.#dirty) this.#show(this.defaultChecked);
else this.#show(this.checked);
}
/** The form was reset: back where the checked attribute says, and the attribute leads again. */
formResetCallback() {
this.#dirty = false;
this.#show(this.defaultChecked);
}
/** The browser gives back where the person left the switch, after Back: "on" or "off". */
formStateRestoreCallback(state) {
this.checked = state === "on";
}
/** A person flipped it: move it, then tell the page, as a checkbox does. */
#flip() {
this.checked = !this.checked;
this.dispatchEvent(new Event("input", { bubbles: true, composed: true }));
this.dispatchEvent(new Event("change", { bubbles: true }));
}
/** Shows on or off everywhere: the state for CSS, the tree, the form's value and saved state, and the validity. */
#show(on) {
if (on) this.#internals.states.add("checked");
else this.#internals.states.delete("checked");
this.#internals.ariaChecked = String(on);
this.#internals.setFormValue(on ? this.value : null, on ? "on" : "off");
if (on || !this.hasAttribute("required")) this.#internals.setValidity({});
else this.#internals.setValidity({ valueMissing: true }, "Please turn this switch on.");
}- Lines 2 and 4 make it form-associated. Its internals are listed for checkers like axe, as in lesson 15.3.
- Line 3 watches three attributes. Line 5 is the dirty flag.
- Lines 14 to 22 are the click and the keys.
- Lines 29 to 39 let the attribute lead, until a flip, and bring it back on a reset.
- Lines 42 to 44 restore after Back. Lines 47 to 51 tell the page about a person's flip.
- Lines 54 to 60 set the state, the tree, the value and its saved state, and the validity.
Further down, the class has the same members as the kit's search box: form, name, a value you can set, validity, and the two checks. It also has checked and defaultChecked. The JSDoc and custom-elements.json document them, with the input and change events and --tea-motion.
Here is the finished switch next to a checkbox, case by case:
| When you | A native checkbox | The kit's tea-toggle |
|---|---|---|
| Leave it off and send the form | Sends nothing for it. | Sends nothing for it. |
| Turn it on and send the form | Sends on, or its value. | Sends on, or its value. |
Click it, then read the checked attribute | The attribute hasn't moved. It still says where it started. | The attribute hasn't moved. It still says where it started. |
| Reset the form | It goes back to its checked attribute. | It goes back to its checked attribute. |
| Leave the page and press Back | It comes back where you left it. | It comes back where you left it, from the state it saved. |
| Hold Space down | It flips once, when you let go. | It flips once, when you let go. |
| Press Enter in a form | The form is sent. | It flips, as the APG allows. |
| Put it in a disabled fieldset | No clicks, no focus, and the form skips it. | No clicks, no focus, and the form skips it. |
The course's test runs pages from earlier lessons with kitAfter165 and kitAfter171: lessons 13.2, 14.1, 15.1, 15.2, and 15.3. Every printed line, box, color, and focus stays the same, and the axe audit still passes. Chrome's tree adds one thing: each switch is now marked not invalid, as a checkbox is, because it's a form control. And one thing changed on purpose: once someone flips a switch, its checked attribute no longer moves it.
Why it matters: the kit's switch now works in a form the way a checkbox does, from plain HTML.
Common mix-ups
- "An off switch sends off." No. It sends nothing, like an unticked checkbox. The form has no entry for it.
- "The checked attribute shows where the switch is." No. It shows where it started. The
checkedproperty and:state(checked)show where it is now. - "A reset turns every switch off." No. A reset goes back to the
checkedattribute, so a switch that started on comes back on. - "A switch that sends nothing when off needs no state." No. Without
"off"saved, Back can't restore it, and it starts from its attribute again. - "Flip it on every keydown." No. A held key repeats
keydown. Flip on Space'skeyup, and skip Enter's repeats. - "Setting checked from a script should fire change." No. A checkbox fires
inputandchangeonly for a person's flip. - "A disabled switch needs ariaDisabled and a tabindex of -1." No. The browser keeps clicks and focus away from a disabled form-associated element, and its tree says disabled.
- "Set role=switch on the host." No. That attribute is the page's to write. Set
internals.role, a default the page can still change. - "Every browser has a native switch now." No. Only Safari draws
<input type="checkbox" switch>as a switch. The others draw a checkbox.
Practice exercises
A ticked checkbox and two kit switches. Predict what line 9 prints when the page opens, then run it.
<form id="order"> <label><input type="checkbox" name="lemon" checked> Lemon</label> <tea-toggle name="milk" checked>Add milk</tea-toggle> <tea-toggle name="extra" value="honey">Add honey</tea-toggle></form><script type="module"> import "./tea-kit/index.js"; const form = document.querySelector("#order"); console.log("Sent:", new URLSearchParams(new FormData(form)).toString());</script><form id="order"> <label><input type="checkbox" name="lemon" checked> Lemon</label> <tea-toggle name="milk" checked>Add milk</tea-toggle> <tea-toggle name="extra" value="honey">Add honey</tea-toggle></form><script type="module"> import "./tea-kit/index.js"; const form = document.querySelector("#order"); console.log("Sent:", new URLSearchParams(new FormData(form)).toString());</script>It prints Sent: lemon=on&milk=on. Lemon and Add milk start on and send on. Add honey is off, so it sends nothing, even with a value.
Predict the two lines this page prints, then run it.
<form id="order"> <tea-toggle name="milk">Add milk</tea-toggle></form><script type="module"> import "./tea-kit/index.js"; const milk = document.querySelector("tea-toggle"); milk.checked = false; milk.setAttribute("checked", ""); console.log("Now:", milk.checked ? "on" : "off"); document.querySelector("#order").reset(); console.log("After reset:", milk.checked ? "on" : "off");</script><form id="order"> <tea-toggle name="milk">Add milk</tea-toggle></form><script type="module"> import "./tea-kit/index.js"; const milk = document.querySelector("tea-toggle"); milk.checked = false; milk.setAttribute("checked", ""); console.log("Now:", milk.checked ? "on" : "off"); document.querySelector("#order").reset(); console.log("After reset:", milk.checked ? "on" : "off");</script>It prints Now: off, then After reset: on. Line 7 made the switch dirty, so line 8's attribute doesn't move it. The reset on line 10 clears the flag and goes back to the attribute, which now says on.
The switch is required and off, but the page prints Valid: true. Fix the tea-toggle.js tab. What does the page print then?
<form id="order"> <tea-toggle name="notice" required>I read the allergy notice</tea-toggle></form><script src="tea-toggle.js"></script><script> const form = document.querySelector("#order"); console.log("Valid:", form.checkValidity());</script><form id="order"> <tea-toggle name="notice" required>I read the allergy notice</tea-toggle></form><script src="tea-toggle.js"></script><script> const form = document.querySelector("#order"); console.log("Valid:", form.checkValidity());</script>The page stays the same. The tea-toggle.js tab now watches required, sends every change through #show(), and sets valueMissing while the switch is off. The form is invalid, so it prints Valid: false.
The page gives the switch value="oat" after it's on, but the form still sends milk=on. Fix the tea-toggle.js tab. What does the page print then?
<form id="order"> <tea-toggle name="milk" checked>Add milk</tea-toggle></form><script src="tea-toggle.js"></script><script> const form = document.querySelector("#order"); form.querySelector("tea-toggle").setAttribute("value", "oat"); console.log("Sent:", new URLSearchParams(new FormData(form)).toString());</script><form id="order"> <tea-toggle name="milk" checked>Add milk</tea-toggle></form><script src="tea-toggle.js"></script><script> const form = document.querySelector("#order"); form.querySelector("tea-toggle").setAttribute("value", "oat"); console.log("Sent:", new URLSearchParams(new FormData(form)).toString());</script>The page stays the same. In the tea-toggle.js tab, line 3 now watches value too, so the change runs #show(), which hands the form the new value. It prints Sent: milk=oat.
Click Your order, press Tab, then hold Enter for a second and let go. The page prints how many times the switch flipped. Make a held Enter flip it once. What does it print then?
<p>Your order</p><tea-toggle name="milk">Add milk</tea-toggle><script src="tea-toggle.js"></script><script> const milk = document.querySelector("tea-toggle"); let flips = 0; milk.addEventListener("change", () => flips++); milk.addEventListener("keyup", (event) => { if (event.key !== "Enter") return; console.log("Flips:", flips); flips = 0; });</script><p>Your order</p><tea-toggle name="milk">Add milk</tea-toggle><script src="tea-toggle.js"></script><script> const milk = document.querySelector("tea-toggle"); let flips = 0; milk.addEventListener("change", () => flips++); milk.addEventListener("keyup", (event) => { if (event.key !== "Enter") return; console.log("Flips:", flips); flips = 0; });</script>The page stays the same. In the tea-toggle.js tab, line 24 now clicks only when event.repeat is false, so a held Enter flips the switch once. It prints Flips: 1.
When the page opens, it prints change: on, though nobody touched the switch. A checkbox wouldn't. Fix the tea-toggle.js tab. What does the page print when it opens then?
<form id="order"> <tea-toggle name="milk">Add milk</tea-toggle></form><script src="tea-toggle.js"></script><script> const milk = document.querySelector("tea-toggle"); milk.addEventListener("change", () => console.log("change:", milk.checked ? "on" : "off")); milk.checked = true; console.log("A script turned it on");</script><form id="order"> <tea-toggle name="milk">Add milk</tea-toggle></form><script src="tea-toggle.js"></script><script> const milk = document.querySelector("tea-toggle"); milk.addEventListener("change", () => console.log("change:", milk.checked ? "on" : "off")); milk.checked = true; console.log("A script turned it on");</script>The page stays the same. The tea-toggle.js tab now fires input and change only in #flip(), which runs for a click or a key. The script's line 8 fires nothing, so the page prints only A script turned it on. A click still prints change: off.
Check your understanding
Question 1 of 8A switch named milk is off. What does new FormData(form).get("milk") return?
Choose an answer to see the explanation.
Question 2 of 8The page writes <tea-toggle name="milk" checked>. Asha turns it off, then presses Clear order. Where does the switch end?
Choose an answer to see the explanation.
Question 3 of 8What does this page print?
Read the code, then predict<tea-toggle name="milk">Add milk</tea-toggle> <script type="module"> import "./tea-kit/index.js"; const milk = document.querySelector("tea-toggle"); milk.setAttribute("checked", ""); console.log(milk.checked ? "on" : "off"); </script>Choose an answer to see the explanation.
Question 4 of 8Which keys does the APG's switch pattern say should flip a switch?
Choose an answer to see the explanation.
Question 5 of 8Why does the kit's switch save "off" as its state, when it sends nothing while off?
Choose an answer to see the explanation.
Question 6 of 8Which selector styles a switch that is on right now?
Choose an answer to see the explanation.
Question 7 of 8Which browsers draw <input type="checkbox" switch> as a switch?
Choose an answer to see the explanation.
Question 8 of 8Does a disabled switch need ariaDisabled in its internals?
Choose an answer to see the explanation.
Key takeaways
- Only Safari has a native switch,
<input type="checkbox" switch>. A custom one is a form-associated element whose host is the control. - Every flip tells three audiences: the checked state for CSS,
ariaCheckedfor screen readers, andsetFormValue()for the form. - While on, send the
value, or"on". While off, sendnull, and save"off"as the state for Back. - The
checkedattribute is where it starts. After a flip it stops leading, and a reset goes back to it. - Flip on a click, Space's
keyup, and Enter's firstkeydown. Fireinputandchangeonly for a person's flip. - Set the role,
ariaChecked, andariaRequiredin the internals. The browser handles disabled. - Style with
:state(checked), never[checked], and keep forced colors, right to left, and reduced motion working.
Remember the one-liner.
A switch is a checkbox with a different look. It sends its value only while on, starts where its attribute says, and tells the form, the screen reader, and CSS on every flip.
Sources
The facts on this page come from these standards, docs, source files, and posts:
- The switch attribute of the input element, HTML Standard.
- An HTML Switch Control, WebKit.
- Switch pattern, W3C WAI-ARIA Authoring Practices Guide.
- Creating a form-associated custom element, HTML Standard.
- Constructing the entry list, HTML Standard.
- ElementInternals: setFormValue() method, MDN.
- The checked attribute and dirty checkedness, HTML Standard.
- HTML attributes vs DOM properties, Jake Archibald.
- switch.ts at v3.15.0: checked, defaultChecked, and the reset, Web Awesome.
- Custom element reactions, HTML Standard.
- Enter, it screams... I mean, it streams, Westbrook Johnson, DEV.
- cr_toggle.ts at 158.0.8127.18: onKeyDown_() and onKeyUp_(), Chromium.
- KeyboardEvent: repeat property, MDN.
- ElementInternals: role property, MDN.
- ElementInternals, instance properties included from ARIA, MDN.
- ax_node_object.cc at 158.0.8127.18: AXNodeObject::IsRequired(), Chromium.
- CustomStateSet: matching the custom state of a custom checkbox element, MDN.
- :state(), MDN.
- Reflection and Custom States in Web Components, Cory LaViska.
- <input type="checkbox" switch>, web-features, on Web Platform Status.
- browser-compat-data, MDN.
Support data comes from MDN's browser-compat-data, and the native switch's status from web-features.
Coming next: Build a button. It builds a button that submits and resets its form like the real one, and shows what it takes for Enter to send a form.