Build a button
Build a web component submit button that sends with requestSubmit(), resets its form, works with Space, Enter, and implicit submission, and styles its states.
- 01Make a custom element act like a buttonGive it the role button through its internals, a place in the Tab order, and Space and Enter that click it the way a native button does.
- 02Submit and reset its formSend with
requestSubmit()and no argument, clear withreset(), send the button's name and value, and know whysubmit()andrequestSubmit(this)go wrong. - 03Know what only a native button can doHandle Enter in a form with two text fields, style focus, pressed, and disabled, and slot a native button when you need commands or the default button.
How do you build a button web component?
It's Saturday at Leaf and Kettle. Meena wants the order form to match the shop. So she swaps its two plain buttons, Place order and Start over, for a tag of her own, tea-button. It has a green border and round corners. It looks right.
Then Asha tries it. She types her name and her table number, and clicks Place order. Nothing happens. She presses Enter. Nothing. She presses Tab, and focus jumps past both buttons. What does a real button do that Meena's tag doesn't?
A button web component is a form-associated custom element whose host is the button. It takes focus, has the role button, and clicks on Space and Enter. A click asks its form to send itself with requestSubmit(), or to clear itself with reset(). One thing stays out of reach. Enter in a form with two text fields needs a real submit button.
Here is Meena's form. Try what Asha tried:
1<form id="order">2 <p><label>Name <input name="who"></label></p>3 <p><label>Table <input name="table" type="number"></label></p>4 <tea-button>Place order</tea-button>5 <tea-button type="reset">Start over</tea-button>6</form>7<script src="tea-button.js"></script>8<script>9 const form = document.querySelector("#order");10 form.addEventListener("submit", (event) => {11 event.preventDefault();12 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");13 });14</script>- Lines 2 and 3 are Name and Table. Lines 4 and 5 are Meena's two buttons.
- Lines 10 to 13 stop the real send, which would load a new page in the Result. Line 12 prints what the form would send. Its second part,
event.submitter, adds the button that sent it, as a real send does.
Type Asha and 4, then click Place order. Nothing prints. Press Enter in Table: still nothing. Press Tab, and focus skips both buttons. Start over clears nothing either.
The tea-button.js tab shows why. Its class draws a border around a slot, and that's all. It's the same kind of lookalike as in lesson 5.7, which sat next to a real button and sent nothing.
Someone paints a doorbell on the shop's front door. It's the right size and the right color. Visitors press it, and nothing rings inside, because no wire runs from it to the chime.
- In real life: The painted doorbell
- In JavaScript: Meena's
tea-button.js, a look and nothing else - In real life: Pressing it
- In JavaScript: A click, Space, or Enter
- In real life: The wire to the chime
- In JavaScript:
requestSubmit()andreset() - In real life: The chime inside
- In JavaScript: The form sends or clears
Build a custom button the way the browser builds a native one. Make the host the control, with a role, a tab stop, and keys. On a press, ask the form to send with requestSubmit() or to clear with reset(). Then add a real submit button wherever Enter must work.
This lesson builds tea-button the way lesson 17.1 built the switch, one piece at a time. It's a form-associated custom element, from lesson 16.1. Those work in Chrome 77, Firefox 98, and Safari 16.4 and later.
What does a native button do that a custom element doesn't?
Quite a lot. Here is the same form with two native <button> elements, on lines 4 and 5. The tea-button.js tab is gone, and line 13 prints when the form resets:
1<form id="order">2 <p><label>Name <input name="who"></label></p>3 <p><label>Table <input name="table" type="number"></label></p>4 <button name="pay" value="card">Place order</button>5 <button type="reset">Start over</button>6</form>7<script>8 const form = document.querySelector("#order");9 form.addEventListener("submit", (event) => {10 event.preventDefault();11 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");12 });13 form.addEventListener("reset", () => console.log("Starting over"));14</script>Type Asha and 4, and click Place order: Sent: who=Asha&table=4&pay=card. Line 4's name and value came along. Press Enter in Table: the same line again. Click Start over: Starting over, and both boxes empty.
The HTML Standard gives a native button all of that. A form-associated custom element gets some of it for free. The rest, your class must copy. Read each row across: what a native button does, whether any form-associated element gets it, and what tea-button will do.
| What a native button does | Does a form-associated element get it? | What tea-button does |
|---|---|---|
| It has the role button. | No. Its role is generic. | It sets internals.role to button. |
| Tab reaches it. | No. | It sets tabIndex to 0, unless the page wrote a tabindex. |
| Space and Enter click it. | No. | Its key listeners call click(). |
type picks submit, reset, or button. | No. The class reads the attribute. | It reads type on each press. |
The button that sends adds its name and value. | No. It can't be the submitter. | It lends the form its value while it sends. |
form joins a form it isn't inside. | Yes. The browser reads form. | Nothing to write. |
disabled, or a disabled fieldset, turns it off. | Yes. No clicks, no focus, and :disabled matches. | Nothing to write but a style. |
| Enter in a text box clicks it. | No. It's never the default button. | Nothing. The page adds a native submit button. |
formaction and the other form overrides change one send. | No. | Nothing. They need a native submitter. |
commandfor opens a dialog or popover. | No. Only a native button invokes commands. | Nothing. Slot a native button for commands. |
- Rows 1 to 5 are your class's job. The role, the tab stop, the keys, the type, and the name and value. The next sections build them.
- Rows 6 and 7 come free. The browser reads
formanddisabledfor any form-associated element (lesson 16.1 and lesson 16.4). - Rows 8 to 10 belong to native buttons. The standard gives them only to a real submit button. The end of the lesson shows how to get them back.
Copy the native names, too: type, name, value, form, and disabled. Why it matters: people already know them, so a page can swap a native button for tea-button and keep its markup.
How do you make a custom element act like a button?
Start with the parts people use without thinking: what it is, how to reach it, and which keys press it. Here is tea-button.js, made to act like a button:
class TeaButton extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
constructor() {
super();
this.#internals.role = "button";
this.attachShadow({ mode: "open" }).innerHTML = `<style>
:host { display: inline-block; padding: 4px 8px; border: 2px solid seagreen; border-radius: 8px; cursor: pointer; }
</style><slot></slot>`;
this.addEventListener("keydown", (event) => {
if (event.key === "Enter") this.click();
if (event.key === " ") event.preventDefault();
});
this.addEventListener("keyup", (event) => {
if (event.key === " ") this.click();
});
}
connectedCallback() {
if (!this.hasAttribute("tabindex")) this.tabIndex = 0;
}
}
customElements.define("tea-button", TeaButton);- Line 2 makes it form-associated, and line 3 asks for its internals, as in lesson 16.1.
- Line 7 gives the host the role button through its internals (lesson 13.2). The tag gets no
roleattribute, so a page can still write its own. - Lines 11 to 14 listen for keydown. Enter clicks the button at once. Space only stops the page from scrolling.
- Lines 15 to 17 click the button when Space comes back up.
- Line 21 puts it in the Tab order, unless the page wrote a tabindex (lesson 14.1).
Why Enter on keydown, and Space on keyup? That's what a native button does. Westbrook Johnson explains it. Space clicks a button when the key comes up. Enter clicks when it goes down. And a held key sends keydown again and again, so a held Enter clicks again and again. Test it against a real button:
1<p>Your order</p>2<button>Place order</button>3<tea-button>Place order</tea-button>4<script src="tea-button.js"></script>5<script>6 for (const button of document.querySelectorAll("button, tea-button")) {7 button.addEventListener("click", () => console.log("click on", button.localName));8 }9</script>- Line 2 is a native button. Line 3 is tea-button, with the file above.
- Lines 6 to 8 print each click, with the tag that got it.
Click Your order, press Tab, and hold Enter for a second. Let go, then hold Space and let go. Press Tab, and do the same on tea-button.
Both print the same lines. While Enter is down, each prints click on button or click on tea-button again and again. Space prints it once, when you let go. The course's test held each key for three keydowns, and each button printed three clicks for Enter and one for Space. Chrome's tree lists them the same way too:
button "Place order"
button "Place order"Line 1 is the native button, and line 2 is tea-button. Both are buttons named Place order.
Chrome's own settings button, cr-button, makes another choice. It skips the repeats, so a held Enter clicks once. The APG's button pattern only says that Space and Enter both press a button. The kit copies the native button. Whichever you pick, write it in your docs.
Why it matters: keyboard users press Space and Enter on anything that looks like a button. A button that matches the real one never surprises them.
How does a custom button submit a form with requestSubmit()?
The button acts like one now. But a click still sends nothing, because nothing tells the form. A form has two methods that send it, submit() and requestSubmit(), and requestSubmit() can also name a button. That makes three things to try. In this playground, the form sends to a hidden frame called kitchen, so a real send stays out of the way:
1<iframe name="kitchen" hidden></iframe>2<form id="order" target="kitchen" action="about:blank">3 <p><label>Name <input name="who" required></label></p>4 <tea-button>Place order</tea-button>5</form>6<script src="tea-button.js"></script>7<script>8 const form = document.querySelector("#order");9 document.querySelector("iframe").addEventListener("load", () => console.log("The kitchen got an order"));10 form.addEventListener("submit", (event) => {11 event.preventDefault();12 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");13 });14</script>submit() skips the check and the submit event. The empty order went out, and so did Asha's. It prints The kitchen got an order twice.
- Line 1 is the hidden kitchen frame. Line 2 sends the form there, with its target.
- Line 3 is a required Name. Line 9 prints when the kitchen gets an order.
Press Place order with Name empty. Then type Asha, and press it again.
form.submit()printsThe kitchen got an ordertwice. The empty order went out too.form.requestSubmit(this)prints nothing. Each press throws a TypeError: "The specified element is not a submit button."form.requestSubmit()stops the first press at Name, with Chrome's message "Please fill out this field." The second press printsSent: who=Asha.
requestSubmit() with no argument works like a click on a real submit button. The form checks its fields, fires submit, and then sends.MDN sums up the difference. submit() sends the form, and that's all. requestSubmit() acts as if a submit button were clicked. The form checks its fields, then fires submit. The HTML Standard's form submission algorithm skips both steps only for submit(). So the empty order reached the kitchen, and the listener that prints Sent never ran. The JavaScript path's form events lesson covers the submit event itself.
At Leaf and Kettle, order slips go to Ravi at the counter. He checks that each one has a name, then calls it out so everyone hears. A slip pushed through the kitchen hatch skips Ravi. Nobody checks it, and nobody hears it.
- In real life: Handing the slip to Ravi
- In JavaScript:
requestSubmit() - In real life: Ravi checks for a name
- In JavaScript: The form's checks, like
required - In real life: He calls the order out
- In JavaScript: The
submitevent - In real life: Pushing it through the hatch
- In JavaScript:
submit(): no checks, no event
Why does requestSubmit(this) throw? The HTML Standard says its argument must be a submit button. That means a native <button> that submits, or an <input> of type submit or image. A form-associated custom element is a submittable element: the form sends its value. But it's never a button. So call requestSubmit() with no argument. Then the form itself is the submitter.
The submitter, and the button's name and value
A submit event has a submitter: the button that sent the form. A native submit button with a name also adds its own name and value to what's sent. Here a native button and tea-button share the name pay. The tab is the playground's third version:
1<form id="order">2 <p><label>Name <input name="who" value="Asha"></label></p>3 <button name="pay" value="cash">Pay cash</button>4 <tea-button name="pay" value="card">Pay by card</tea-button>5</form>6<script src="tea-button.js"></script>7<script>8 const form = document.querySelector("#order");9 form.addEventListener("submit", (event) => {10 event.preventDefault();11 console.log("Submitter:", event.submitter?.textContent ?? null);12 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");13 });14</script>- Line 3 is a native button. Line 4 is tea-button. Both have the name pay.
- Line 11 prints the submitter's words, or null. Line 12 prints what the form would send.
Click Pay cash: Submitter: Pay cash and Sent: who=Asha&pay=cash. Click Pay by card: Submitter: null and Sent: who=Asha, with no pay at all.
With no argument, the form is the submitter, and the event reports that as null. And the standard sends a button's name and value only for the button that sent the form. So pay=card is never sent. Line 12 passes the submitter to FormData, which adds a native submitter's entry, as the real send does. Without it, Pay cash would print only who=Asha too.
The fix is to lend the form the button's value while it sends. Here is the new tab:
class TeaButton extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
constructor() {
super();
this.#internals.role = "button";
this.attachShadow({ mode: "open" }).innerHTML = `<style>
:host { display: inline-block; padding: 4px 8px; border: 2px solid seagreen; border-radius: 8px; cursor: pointer; }
</style><slot></slot>`;
this.addEventListener("keydown", (event) => {
if (event.key === "Enter") this.click();
if (event.key === " ") event.preventDefault();
});
this.addEventListener("keyup", (event) => {
if (event.key === " ") this.click();
});
this.addEventListener("click", () => this.#send());
}
connectedCallback() {
if (!this.hasAttribute("tabindex")) this.tabIndex = 0;
}
#send() {
this.#internals.setFormValue(this.getAttribute("value") ?? "");
this.#internals.form?.requestSubmit();
this.#internals.setFormValue(null);
}
}
customElements.define("tea-button", TeaButton);- Line 18 now calls
#send(). - Line 26 hands the form the button's value, which the form sends under its name. Line 27 sends. Line 28 takes the value back, so another button's send doesn't carry it.
1<form id="order">2 <p><label>Name <input name="who" value="Asha"></label></p>3 <button name="pay" value="cash">Pay cash</button>4 <tea-button name="pay" value="card">Pay by card</tea-button>5</form>6<script src="tea-button.js"></script>7<script>8 const form = document.querySelector("#order");9 form.addEventListener("submit", (event) => {10 event.preventDefault();11 console.log("Submitter:", event.submitter?.textContent ?? null);12 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");13 });14</script>Click Pay by card. Line 11 prints Submitter: null, and line 12 prints Sent: who=Asha&pay=card. It works because requestSubmit() checks the form, fires submit, and builds the list of entries before it returns. Material Web's buttons also call setFormValue() with their value just before requestSubmit().
Why it matters: a page might check which button sent the form. With a custom button, event.submitter is null, so read the form's entries instead.
How does a custom button reset its form?
With form.reset(). The HTML Standard gives a reset two steps. First the form fires a reset event, which a listener can cancel. Then each control goes back to where it started. An input goes back to its value attribute. A form-associated element runs its formResetCallback(), as in lesson 16.4.
A press now does one of three things, so the tab reads the type attribute. Here is Start over, beside a text box and the kit's switch:
1<link rel="stylesheet" href="tea-kit/tokens.css">2<form id="order">3 <p><label>Name <input name="who" value="Asha"></label></p>4 <p><tea-toggle name="oat" checked>Add oat milk</tea-toggle></p>5 <tea-button type="reset">Start over</tea-button>6</form>7<script type="module">8 import "./tea-kit/index.js";9 import "./tea-button.js";10 const form = document.querySelector("#order");11 form.addEventListener("reset", () => {12 console.log("reset: Name is", form.elements.who.value);13 setTimeout(() => console.log("then: Name is", form.elements.who.value, "and oat milk is", form.elements.oat.checked ? "on" : "off"));14 });15</script>- Line 3 starts as Asha, and line 4 starts on. Line 5 is Start over, with type="reset".
- Lines 11 to 14 print Name when the reset event fires, and again a moment later.
class TeaButton extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
constructor() {
super();
this.#internals.role = "button";
this.attachShadow({ mode: "open" }).innerHTML = `<style>
:host { display: inline-block; padding: 4px 8px; border: 2px solid seagreen; border-radius: 8px; cursor: pointer; }
</style><slot></slot>`;
this.addEventListener("keydown", (event) => {
if (event.key === "Enter") this.click();
if (event.key === " ") event.preventDefault();
});
this.addEventListener("keyup", (event) => {
if (event.key === " ") this.click();
});
this.addEventListener("click", (event) => {
setTimeout(() => {
if (!event.defaultPrevented) this.#activate();
});
});
}
connectedCallback() {
if (!this.hasAttribute("tabindex")) this.tabIndex = 0;
}
#activate() {
const form = this.#internals.form;
const type = this.getAttribute("type") ?? "submit";
if (!form || type === "button") return;
if (type === "reset") return form.reset();
this.#internals.setFormValue(this.getAttribute("value") ?? "");
form.requestSubmit();
this.#internals.setFormValue(null);
}
}
customElements.define("tea-button", TeaButton);- Lines 29 to 37 are
#activate(). Line 31 reads the type, with submit as the default, as on a native button. Line 32 stops for type="button", or with no form. Line 33 resets. - Lines 18 to 22 wait one task before
#activate(). By then, every click listener on the page has run. If one calledpreventDefault(), line 20 skips the press, as on a native button. Lesson 16.5's search box waited for the same reason.
Change Name to Ravi, turn oat milk off, and press Start over. It prints reset: Name is Ravi, then then: Name is Asha and oat milk is on.
The first line shows the event comes before the reset, so a page can still say no. The second shows both controls back at their attributes. The switch went back because lesson 17.1 gave it a reset callback. The button only asked.
Why it matters: a reset button never clears anything itself. It asks the form, and each control knows its own start.
Why doesn't Enter submit a form with a custom button?
Because Enter presses the form's default button: its first real submit button. The HTML Standard calls this implicit submission. A custom button is never a submit button, so it's never the default button. So what does Enter do in a form with none? The standard has two rules:
- With one text field, Enter sends the form from the form itself.
- With two or more, Enter does nothing.
The fields that count are inputs where you type one line: text, search, email, url, tel, password, number, and the date and time inputs. The standard calls them fields that block implicit submission. A checkbox doesn't count, and neither does a textarea. Try three forms:
1<form id="order">2 <p><label>Name <input name="who" value="Asha"></label></p>3 <p><label><input type="checkbox" name="lemon" checked> Lemon</label></p>4 <tea-button>Place order</tea-button>5</form>6<script src="tea-button.js"></script>7<script>8 const form = document.querySelector("#order");9 form.addEventListener("submit", (event) => {10 event.preventDefault();11 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString(), "by", event.submitter?.localName ?? "the form");12 });13</script>There's no real submit button, and only one field that blocks Enter. A checkbox doesn't count. So the form sends itself, with no submitter: Sent: who=Asha&lemon=on by the form.
- Line 2 is Name. Lines 3 and 4 change with each button above.
- Line 11 prints what's sent, then the submitter's tag, or "the form".
Click in Name and press Enter.
- Name and a checkbox:
Sent: who=Asha&lemon=on by the form. One text field, so the form sends itself. - Name and Table: nothing at all. Two text fields, and no real submit button.
- Add a hidden native button:
Sent: who=Asha&table=4 by button. It's the default button, and Enter clicks it.
Asha says "That's all" at the counter. If her order is one line, Ravi sends it. If it's longer, he sends it only when he taps Order on the till. A sticker that says Order, stuck beside the till, does nothing.
- In real life: Asha says "That's all"
- In JavaScript: Enter in a text field
- In real life: An order of one line
- In JavaScript: A form with one field that blocks Enter
- In real life: The Order button on the till
- In JavaScript: The default button, a real submit button
- In real life: A sticker that says Order
- In JavaScript: A custom button: never the default
So give a form with two text fields a native submit button. It can stay hidden, like the third form's <button hidden>. Hidden doesn't matter: Enter still fires a click at it. A disabled one, though, stops Enter completely. Ionic's buttons do this for you. Each one adds a native button with display: none to its form, and a click on the Ionic button clicks it. The platform-provided behaviors explainer calls that an older method. It breaks encapsulation, and the extra element can change the layout.
Why it matters: people press Enter to send forms. With two text fields and only custom buttons, Enter quietly does nothing.
How do you style a custom button's focus, pressed, and disabled states?
A native button changes its look in three ways: a focus ring, a pressed look, and a faded look when it's off. tea-button needs all three. Here is the finished file:
class TeaButton extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
constructor() {
super();
this.#internals.role = "button";
this.attachShadow({ mode: "open" }).innerHTML = `<style>
:host { display: inline-block; padding: 4px 8px; border: 2px solid seagreen; border-radius: 8px; cursor: pointer; }
:host(:focus-visible) { outline: 2px solid seagreen; outline-offset: 2px; }
:host(:active), :host(:state(active)) { box-shadow: inset 0 0 0 2px seagreen; }
:host(:disabled) { cursor: default; opacity: 0.5; }
</style><slot></slot>`;
this.addEventListener("keydown", (event) => {
if (event.key === "Enter") this.click();
if (event.key !== " ") return;
event.preventDefault();
this.#internals.states.add("active");
});
this.addEventListener("keyup", (event) => {
if (event.key !== " " || !this.#internals.states.has("active")) return;
this.#internals.states.delete("active");
this.click();
});
this.addEventListener("blur", () => this.#internals.states.delete("active"));
this.addEventListener("click", (event) => {
setTimeout(() => {
if (!event.defaultPrevented) this.#activate();
});
});
}
connectedCallback() {
if (!this.hasAttribute("tabindex")) this.tabIndex = 0;
}
#activate() {
const form = this.#internals.form;
if (!form || this.type === "button") return;
if (this.type === "reset") return form.reset();
this.#internals.setFormValue(this.value);
form.requestSubmit();
this.#internals.setFormValue(null);
}
get type() {
const type = this.getAttribute("type")?.toLowerCase();
return type === "reset" || type === "button" ? type : "submit";
}
get value() {
return this.getAttribute("value") ?? "";
}
get disabled() {
return this.hasAttribute("disabled");
}
}
customElements.define("tea-button", TeaButton);- Line 10 draws a ring with
:host(:focus-visible), as lesson 14.1 did. Chrome shows it after Tab, not after a mouse click. - Line 11 draws the pressed look, a thicker border inside. Line 12 fades a disabled button.
- Lines 14 to 24 add a custom state, active, while Space is down, and click on keyup only if it's there. Line 25 drops it if focus leaves first.
- Lines 46 to 57 are three properties a native button has: type, value, and disabled.
Why a custom state for Space? Hold Space on a native button, and Chrome matches :active, the pressed state. Hold Space on a custom element, and it doesn't. There, :active matches while the mouse is down. So line 18 adds active, and line 11 styles :state(active) beside :active (lesson 12.3).
1<form id="order">2 <tea-button>Place order</tea-button>3 <tea-button disabled>Pay later</tea-button>4 <fieldset disabled>5 <legend>Gift</legend>6 <tea-button type="button">Add gift wrap</tea-button>7 </fieldset>8</form>9<script src="tea-button.js"></script>10<script>11 for (const button of document.querySelectorAll("tea-button")) {12 const says = (selector) => (button.matches(selector) ? "yes" : "no");13 console.log(`${button.textContent}: :disabled ${says(":disabled")}, [disabled] ${says("[disabled]")}, .disabled ${button.disabled}`);14 }15</script>- Line 2 is a plain button. Line 3 has the disabled attribute. Lines 4 to 7 are a gift fieldset that's disabled, with a button inside.
- Line 13 prints, for each button, whether it matches
:disabledand[disabled], and its disabled property.
Place order: :disabled no, [disabled] no, .disabled falsePay later: :disabled yes, [disabled] yes, .disabled trueAdd gift wrap: :disabled yes, [disabled] no, .disabled false
Click in the Result, press Tab, and hold Space. Place order gets its ring and its pressed look. Press Tab again, and focus skips both faded buttons.
The tea room's lamp has its own switch. The room also has a main switch by the door. If the main switch is off, the lamp stays dark, whatever its own switch says.
- In real life: The lamp's own switch
- In JavaScript: The button's disabled attribute
- In real life: The room's main switch
- In JavaScript: A
<fieldset disabled>around it - In real life: Looking only at the lamp's switch
- In JavaScript:
[disabled] - In real life: Asking whether the lamp can light
- In JavaScript:
:disabled
So style :disabled. It matches a form-associated element that's off for either reason, as lesson 16.4 showed. [disabled] only sees the button's own attribute. Chrome's cr-button isn't form-associated, so :disabled never matches it. It styles :host([disabled]) instead. For a form-associated button, use :disabled.
The disabled property copies the native button too. It reads only the attribute. A native button in a disabled fieldset says false as well. Match :disabled when you need the whole answer.
What about formDisabledCallback()? Lesson 16.4 used it to turn off an input inside a shadow root. This button needs nothing there. The browser already gives a disabled form-associated element no clicks and no focus. If it has focus when it turns off, Chrome moves focus away, and line 25 drops the pressed look.
Why it matters: people see a button's state before they press it. Ring, pressed, and faded should look the same as on every other button.
Can a button inside shadow DOM submit a form?
Not the page's form. Lesson 16.5's wrapper put the real input in its shadow root. For a button, that breaks the form. A control finds its form in its own tree (lesson 16.1). A button in a shadow root sits in the shadow tree, and the form is outside it. Try that, then try a button slotted from the page:
1<form id="order">2 <p><label>Name <input name="who" value="Asha"></label></p>3 <p><label>Table <input name="table" value="4"></label></p>4 <tea-button name="pay" value="card">Place order</tea-button>5</form>6<script src="tea-button.js"></script>7<script>8 const form = document.querySelector("#order");9 form.addEventListener("submit", (event) => {10 event.preventDefault();11 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString(), "by", event.submitter?.localName ?? "the form");12 });13</script>The native button sits in tea-button's shadow root, and the form is outside it. So the button has no form owner. The click sends nothing, and Enter does nothing.
Click Place order. Then click in Name and press Enter.
- Button in the shadow root: nothing, twice. The button's form is null.
- Slot the page's button:
Sent: who=Asha&table=4&pay=card by button, twice. The click sent it, and Enter clicked it.
The phone in a shop's display case is a real phone. It lights up, and its buttons work. But it has no SIM card, so it can't call anyone. Your own phone, in a nice new case, still can.
- In real life: The phone on the display stand
- In JavaScript: A
<button>in the shadow root - In real life: It has no SIM card
- In JavaScript: Its form is null
- In real life: Your own phone, in a new case
- In JavaScript: A slotted
<button>with tea-button's styles - In real life: It still calls anyone
- In JavaScript: It still sends, takes Enter, and runs commands
So slot it. The page writes a real <button> inside tea-button, and the shadow root shows it with a slot, styled with ::slotted() (lesson 11.3). The button stays in the page's tree, inside the form. Every native power stays with it:
- Enter clicks it, because it can be the default button.
- Its name and value are sent, and
event.submitteris the button. formactionand the other overrides work, and:defaultmatches it.commandforworks, with any id in the page. It's an attribute of a button, so a custom element can never send commands (lesson 14.5).- It works before JavaScript loads, or without it.
The cost is the markup: the page writes the button, and the component only styles it. Lesson 16.5's choice holds here too. Slot when the page owns the control, or when it must work without JavaScript. Build from scratch when the host itself must be the button.
Why not extend HTMLButtonElement?
A customized built-in, <button is="tea-button">, keeps every native power. But Safari doesn't support them, and WebKit has said it won't (lesson 5.7). In Safari it stays a plain button, and your class never runs.
Platform-provided behaviors, a proposal for buttons
Microsoft's Edge team has proposed a way to borrow a native button's behavior. In its explainer, a class declares static activationBehavior = HTMLButtonBehavior, next to formAssociated. Its host would then submit and reset like a native button, take Enter as the default button, and match :default.
Chrome has a developer trial behind its Experimental Web Platform features flag, since Chrome 149. The change to the HTML Standard, pull request 12409, is open. Firefox and Safari haven't said what they think. Until it ships everywhere, build the button the way this lesson does (lesson 5.7 has the bigger picture).
Why it matters: the place you put a native button decides what it can do. Inside a shadow root, it can't reach the page's form.
Adding a button to the tea kit
Back to Meena's form. The kit's new version, kitAfter172, adds tea-button: the finished button, with the kit's styles. Here is her order form with it:
1<link rel="stylesheet" href="tea-kit/tokens.css">2<form id="order">3 <p><label>Name <input name="who" required></label></p>4 <p><label>Table <input name="table" type="number" value="4"></label></p>5 <p><tea-toggle name="oat">Add oat milk</tea-toggle></p>6 <button hidden></button>7 <tea-button name="pay" value="counter">Place order</tea-button>8 <tea-button type="reset">Start over</tea-button>9</form>10<script type="module">11 import "./tea-kit/index.js";12 const form = document.querySelector("#order");13 form.addEventListener("submit", (event) => {14 event.preventDefault();15 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");16 });17 form.addEventListener("reset", () => console.log("Starting over"));18</script>- Line 3 is a required Name, and line 4 is Table. Line 5 is the kit's switch.
- Line 6 is a hidden native button, for Enter. Line 7 is Place order, with a name and a value. Line 8 is Start over.
- Press Place order. Chrome shows "Please fill out this field." at Name, and nothing prints.
- Type Asha in Name and press Enter:
Sent: who=Asha&table=4. The hidden button sent it. - Click Add oat milk, press Tab to reach Place order, and press Space:
Sent: who=Asha&table=4&oat=on&pay=counter. - Press Start over:
Starting over, and the form goes back to its start.
Here is the class, from tea-kit/tea-button.js:
export class TeaButton extends HTMLElement {
static formAssociated = true;
#internals = attachInternals(this);
constructor() {
super();
this.#internals.role = "button";
this.attachShadow({ mode: "open" });
this.shadowRoot.adoptedStyleSheets = [base, sheet];
this.shadowRoot.append(template.content.cloneNode(true));
this.addEventListener("keydown", (event) => {
if (event.key === "Enter") this.click();
if (event.key !== " ") return;
event.preventDefault();
this.#internals.states.add("active");
});
this.addEventListener("keyup", (event) => {
if (event.key !== " " || !this.#internals.states.has("active")) return;
this.#internals.states.delete("active");
this.click();
});
this.addEventListener("blur", () => this.#internals.states.delete("active"));
this.addEventListener("click", (event) => {
setTimeout(() => {
if (!event.defaultPrevented) this.#activate();
});
});
}
connectedCallback() {
if (!this.hasAttribute("tabindex")) this.tabIndex = 0;
}
/** A press, after every click listener has run: send or clear the form, by type, lending the form this button's value. */
#activate() {
const form = this.#internals.form;
if (!form || this.type === "button") return;
if (this.type === "reset") return form.reset();
this.#internals.setFormValue(this.value);
form.requestSubmit();
this.#internals.setFormValue(null);
}- Lines 2 and 3 make it form-associated, with its internals listed for checkers like axe (lesson 15.3). Line 7 gives it the role button.
- Lines 11 to 21 are Enter and Space, with the active state. Line 22 lets go of it on blur.
- Lines 23 to 27 wait a task after each click. Lines 35 to 42 reset, or lend the value and send.
Further down, it has type, name, value, disabled, and form, as a native button does. The JSDoc and custom-elements.json document them, with the active state and --tea-focus-ring. Here are its styles:
@layer component {
:host { display: inline-block; padding: 4px 8px; border: 2px solid var(--tea-color-leaf, seagreen); border-radius: var(--tea-radius, 8px); background: var(--tea-color-paper, white); color: var(--tea-color-ink, #222); cursor: pointer; }
}
@layer state {
:host(:focus-visible) { outline: 2px solid var(--tea-focus-ring, var(--tea-color-leaf, seagreen)); outline-offset: 2px; }
:host(:active), :host(:state(active)) { box-shadow: inset 0 0 0 2px var(--tea-color-leaf, seagreen); }
:host(:disabled) { cursor: default; opacity: 0.5; }
@media (forced-colors: active) {
:host { border-color: ButtonText; background: ButtonFace; color: ButtonText; }
:host(:disabled) { opacity: 1; border-color: GrayText; color: GrayText; }
}
}- Line 2 matches the kit's light buttons from lesson 12.4: a green border on paper, with ink text.
- Lines 5 to 7 are the ring, the pressed look, and the faded look.
- Lines 8 to 11 use the person's button colors in forced colors mode, and
GrayTextwhile disabled (lesson 15.1).
The course's test runs pages from earlier lessons with kitAfter171 and kitAfter172: lessons 13.2, 15.3, 16.5, and 17.1. Every printed line, box, color, and tree stays the same. Before you ship a button of your own, run lesson 15.3's axe check, and listen to it with a screen reader.
Why it matters: the kit's forms now have buttons that look like the kit and send like the real thing.
Common mix-ups
- "requestSubmit(this) makes my button the submitter." No. It throws a TypeError. Only a native button or a submit input can be named.
- "submit() and requestSubmit() do the same thing." No.
submit()skips the form's checks and thesubmitevent. - "A custom button's name and value are sent like a native button's." No. Only if it lends the form its value while it sends.
- "event.submitter tells you which custom button was pressed." No. It's null after
requestSubmit()with no argument. - "Enter always sends a form." No. With two text fields and no real submit button, Enter does nothing.
- "A hidden submit button can't take Enter." No. Enter clicks the default button even when it's hidden. Only a disabled one stops it.
- ":active matches while Space is held on any button." No. Chrome does that only for native buttons. Add a custom state.
- "[disabled] finds every disabled button." No. A button in a disabled fieldset has no attribute.
:disabledfinds both. - "A custom button needs formDisabledCallback() to turn off." No. The browser already keeps clicks and focus away from it.
- "A native button in a shadow root sends the page's form." No. Its form is null there. Slot it from the page.
- "commandfor works on a custom element with the role button." No. Only a native button sends commands.
Practice exercises
Predict what Enter in Name prints, then click in Name and press Enter.
1<form id="order">2 <p><label>Name <input name="who" value="Asha"></label></p>3 <p><label>Table <input name="table" value="4"></label></p>4 <tea-button>Place order</tea-button>5</form>6<script type="module">7 import "./tea-kit/index.js";8 const form = document.querySelector("#order");9 form.addEventListener("submit", (event) => {10 event.preventDefault();11 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");12 });13</script>1<form id="order">2 <p><label>Name <input name="who" value="Asha"></label></p>3 <p><label>Table <input name="table" value="4"></label></p>4 <tea-button>Place order</tea-button>5</form>6<script type="module">7 import "./tea-kit/index.js";8 const form = document.querySelector("#order");9 form.addEventListener("submit", (event) => {10 event.preventDefault();11 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");12 });13</script>Nothing prints. tea-button is never the form's default button, and with two text fields and no real submit button, the HTML Standard says Enter does nothing.
Predict the two lines this page prints, then run it.
1<form id="order">2 <p><label>Name <input name="who" value="Asha"></label></p>3 <p><tea-toggle name="oat" checked>Add oat milk</tea-toggle></p>4 <tea-button type="reset">Start over</tea-button>5</form>6<script type="module">7 import "./tea-kit/index.js";8 const form = document.querySelector("#order");9 const show = (when) => console.log(`${when}: ${form.elements.who.value}, oat milk ${form.elements.oat.checked ? "on" : "off"}`);10 form.elements.who.value = "Ravi";11 form.elements.oat.checked = false;12 show("Before");13 form.addEventListener("reset", () => setTimeout(() => show("After")));14 document.querySelector("tea-button").click();15</script>1<form id="order">2 <p><label>Name <input name="who" value="Asha"></label></p>3 <p><tea-toggle name="oat" checked>Add oat milk</tea-toggle></p>4 <tea-button type="reset">Start over</tea-button>5</form>6<script type="module">7 import "./tea-kit/index.js";8 const form = document.querySelector("#order");9 const show = (when) => console.log(`${when}: ${form.elements.who.value}, oat milk ${form.elements.oat.checked ? "on" : "off"}`);10 form.elements.who.value = "Ravi";11 form.elements.oat.checked = false;12 show("Before");13 form.addEventListener("reset", () => setTimeout(() => show("After")));14 document.querySelector("tea-button").click();15</script>It prints Before: Ravi, oat milk off, then After: Asha, oat milk on. Line 14 clicks Start over, which calls form.reset(). Name goes back to its value attribute, and the switch to its checked attribute.
Place order throws a TypeError. Fix the tea-button.js tab. What does Place order print then?
1<form id="order">2 <p><label>Name <input name="who" value="Asha"></label></p>3 <tea-button>Place order</tea-button>4</form>5<script src="tea-button.js"></script>6<script>7 const form = document.querySelector("#order");8 form.addEventListener("submit", (event) => {9 event.preventDefault();10 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");11 });12</script>1<form id="order">2 <p><label>Name <input name="who" value="Asha"></label></p>3 <tea-button>Place order</tea-button>4</form>5<script src="tea-button.js"></script>6<script>7 const form = document.querySelector("#order");8 form.addEventListener("submit", (event) => {9 event.preventDefault();10 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");11 });12</script>The page stays the same. In the tea-button.js tab, line 18 now calls requestSubmit() with no argument, so the form is the submitter, and nothing throws. Place order prints Sent: who=Asha.
Add gift wrap sits in a disabled fieldset, but it doesn't fade. Fix the tea-button.js tab. What does the page print then?
1<fieldset disabled>2 <legend>Gift</legend>3 <tea-button type="button">Add gift wrap</tea-button>4</fieldset>5<script src="tea-button.js"></script>6<script>7 const wrap = document.querySelector("tea-button");8 console.log("Opacity:", getComputedStyle(wrap).opacity);9</script>1<fieldset disabled>2 <legend>Gift</legend>3 <tea-button type="button">Add gift wrap</tea-button>4</fieldset>5<script src="tea-button.js"></script>6<script>7 const wrap = document.querySelector("tea-button");8 console.log("Opacity:", getComputedStyle(wrap).opacity);9</script>The page stays the same. In the tea-button.js tab, line 12 now matches :host(:disabled) in place of :host([disabled]). The button has no disabled attribute, but the fieldset turns it off, so it fades. The page prints Opacity: 0.5.
Enter in Name does nothing in this form. Change the page so it sends. What does Enter in Name print then?
1<form id="order">2 <p><label>Name <input name="who" value="Asha"></label></p>3 <p><label>Table <input name="table" value="4"></label></p>4 <tea-button>Place order</tea-button>5</form>6<script type="module">7 import "./tea-kit/index.js";8 const form = document.querySelector("#order");9 form.addEventListener("submit", (event) => {10 event.preventDefault();11 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");12 });13</script>1<form id="order">2 <p><label>Name <input name="who" value="Asha"></label></p>3 <p><label>Table <input name="table" value="4"></label></p>4 <button hidden></button><tea-button>Place order</tea-button>5</form>6<script type="module">7 import "./tea-kit/index.js";8 const form = document.querySelector("#order");9 form.addEventListener("submit", (event) => {10 event.preventDefault();11 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");12 });13</script>Line 4 of the page adds a hidden native button before Place order. It's the form's default button, so Enter clicks it, and the page prints Sent: who=Asha&table=4.
Pay by card has the name pay and the value card, but the form only sends who=Asha. Fix the tea-button.js tab. What does Pay by card print then?
1<form id="order">2 <p><label>Name <input name="who" value="Asha"></label></p>3 <tea-button name="pay" value="card">Pay by card</tea-button>4</form>5<script src="tea-button.js"></script>6<script>7 const form = document.querySelector("#order");8 form.addEventListener("submit", (event) => {9 event.preventDefault();10 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");11 });12</script>1<form id="order">2 <p><label>Name <input name="who" value="Asha"></label></p>3 <tea-button name="pay" value="card">Pay by card</tea-button>4</form>5<script src="tea-button.js"></script>6<script>7 const form = document.querySelector("#order");8 form.addEventListener("submit", (event) => {9 event.preventDefault();10 console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");11 });12</script>The page stays the same. The tea-button.js tab now sends through #send(), which hands the form the value, calls requestSubmit(), and takes the value back. Pay by card prints Sent: who=Asha&pay=card.
Check your understanding
Question 1 of 8What does this page print?
Read the code, then predictPop out in the code editor (opens in a new tab)HTML<form id="order"> <tea-button>Place order</tea-button> </form> <script type="module"> import "./tea-kit/index.js"; const form = document.querySelector("#order"); try { form.requestSubmit(document.querySelector("tea-button")); } catch (error) { console.log(error.name); } </script>Choose an answer to see the explanation.
Question 2 of 8Which call checks the form's fields and fires submit before it sends?
Choose an answer to see the explanation.
Question 3 of 8A custom button calls form.requestSubmit(). What is event.submitter in the submit listener?
Choose an answer to see the explanation.
Question 4 of 8A form has Name and Table text fields and only a custom submit button. What does Enter in Name do?
Choose an answer to see the explanation.
Question 5 of 8A tea-button sits inside a <fieldset disabled>. Which selector matches it?
Choose an answer to see the explanation.
Question 6 of 8A <button> sits in a custom element's shadow root, and the custom element sits in a form. What does a click on the button send?
Choose an answer to see the explanation.
Question 7 of 8When does Space click a native button?
Choose an answer to see the explanation.
Question 8 of 8Does Chrome's :active match a custom button while Space is held down on it?
Choose an answer to see the explanation.
Key takeaways
- A button web component is a form-associated element whose host is the button. It takes the role button from its internals, a tab stop, and clicks on Enter's keydown and Space's keyup.
- Send with
requestSubmit()and no argument.requestSubmit(this)throws, andsubmit()skips the checks and thesubmitevent. event.submitteris null. The button's name and value are sent only if it lends its value while it sends.- Reset with
form.reset(). Theresetevent fires first, then each control goes back to its start. - Enter presses only a real submit button. With two text fields and none, add a native one, hidden if you like.
- Style
:focus-visible,:state(active)for a held Space, and:disabled, which covers fieldsets. - A native button in a shadow root has no form. Slot one from the page for commands, Enter, and pages without JavaScript.
Remember the one-liner.
A custom button copies a native button's role, keys, and attributes, and asks its form to send or clear. Only a real submit button takes Enter.
Sources
The facts on this page come from these standards, docs, source files, and posts:
- The button element, HTML Standard.
- Button pattern, W3C WAI-ARIA Authoring Practices Guide.
- ElementInternals: role property, MDN.
- Enter, it screams... I mean, it streams, Westbrook Johnson, DEV.
- cr_button.ts at 158.0.8127.18: onKeyDown_() and onKeyUp_(), Chromium.
- HTMLFormElement: requestSubmit() method, MDN.
- The requestSubmit() method, HTML Standard.
- Submittable elements, HTML Standard.
- Form submission algorithm, HTML Standard.
- SubmitEvent: submitter property, MDN.
- FormData() constructor, MDN.
- form-submitter.ts at 875a8b6b: the click listener, Material Web.
- Resetting a form, HTML Standard.
- Implicit submission, HTML Standard.
- Field that blocks implicit submission, HTML Standard.
- button.tsx at 597b9e24: renderHiddenButton(), Ionic.
- :state(), MDN.
- :disabled, MDN.
- cr_button.css at 158.0.8127.18: :host([disabled]), Chromium.
- The commandfor attribute, HTML Standard.
- Platform-Provided Behaviors for Custom Elements, Microsoft Edge explainer.
- Add platform-provided behaviors for custom elements & submit behavior, WHATWG HTML pull request 12409.
- Platform-provided behaviors for custom elements, Chrome Platform Status.
- runtime_enabled_features.json5 at 158.0.8127.18: ElementInternalsBehaviors, Chromium.
- browser-compat-data, MDN.
Support data comes from MDN's browser-compat-data.
Coming next: Build an input. It builds a text input with labels, validation, and submission, styled for every state.