completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

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.

By the end, you can
  • 01
    Make 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.
  • 02
    Submit and reset its formSend with requestSubmit() and no argument, clear with reset(), send the button's name and value, and know why submit() and requestSubmit(this) go wrong.
  • 03
    Know 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:

The order form with Meena's lookalike buttonsPop out in the code editor (opens in a new tab)HTML
<form id="order">  <p><label>Name <input name="who"></label></p>  <p><label>Table <input name="table" type="number"></label></p>  <tea-button>Place order</tea-button>  <tea-button type="reset">Start over</tea-button></form><script src="tea-button.js"></script><script>  const form = document.querySelector("#order");  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");  });</script>
ResultLoading…
  • 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.

Real-life analogyA drawing of a doorbell

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() and reset()
In real life: The chime inside
In JavaScript: The form sends or clears
The main idea

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:

The order form with native buttonsPop out in the code editor (opens in a new tab)HTML
<form id="order">  <p><label>Name <input name="who"></label></p>  <p><label>Table <input name="table" type="number"></label></p>  <button name="pay" value="card">Place order</button>  <button type="reset">Start over</button></form><script>  const form = document.querySelector("#order");  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");  });  form.addEventListener("reset", () => console.log("Starting over"));</script>
ResultLoading…

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, and what a custom one must copy
What a native button doesDoes 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 form and disabled for 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:

tea-button.js, acting like a buttonJavaScript
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 role attribute, 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:

A native button and tea-button, side by sidePop out in the code editor (opens in a new tab)HTML
<p>Your order</p><button>Place order</button><tea-button>Place order</tea-button><script src="tea-button.js"></script><script>  for (const button of document.querySelectorAll("button, tea-button")) {    button.addEventListener("click", () => console.log("click on", button.localName));  }</script>
ResultLoading…
  • 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:

Chrome's tree for the two buttonsText
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:

Playground: three ways to send the form
An order form that sends to a hidden frame, with one of three tea-button.js filesPop out in the code editor (opens in a new tab)HTML
<iframe name="kitchen" hidden></iframe><form id="order" target="kitchen" action="about:blank">  <p><label>Name <input name="who" required></label></p>  <tea-button>Place order</tea-button></form><script src="tea-button.js"></script><script>  const form = document.querySelector("#order");  document.querySelector("iframe").addEventListener("load", () => console.log("The kitchen got an order"));  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");  });</script>
ResultLoading…
Try it yourself
The order goes straight to the kitchen

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.

Only line 18 of the tea-button.js tab changes: the click listener.
  • 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() prints The kitchen got an order twice. 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 prints Sent: who=Asha.
Three rows, each a card on the left with an arrow to a result card. submit() goes to a card sent as it is, labelled no check and no submit event. requestSubmit(this) goes to a card TypeError, labelled not a submit button. requestSubmit() goes to a card check, submit, send, labelled submitter: null.submit()sent as it isno check and no submit eventrequestSubmit(this)TypeErrornot a submit buttonrequestSubmit()check, submit, sendsubmitter: null
Only 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.

Real-life analogyThrough the counter, not the kitchen hatch

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 submit event
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:

A native button and tea-button, both named payPop out in the code editor (opens in a new tab)HTML
<form id="order">  <p><label>Name <input name="who" value="Asha"></label></p>  <button name="pay" value="cash">Pay cash</button>  <tea-button name="pay" value="card">Pay by card</tea-button></form><script src="tea-button.js"></script><script>  const form = document.querySelector("#order");  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Submitter:", event.submitter?.textContent ?? null);    console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");  });</script>
ResultLoading…
  • 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:

tea-button.js, lending its value while it sendsJavaScript
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.
The same form, with the lending tabPop out in the code editor (opens in a new tab)HTML
<form id="order">  <p><label>Name <input name="who" value="Asha"></label></p>  <button name="pay" value="cash">Pay cash</button>  <tea-button name="pay" value="card">Pay by card</tea-button></form><script src="tea-button.js"></script><script>  const form = document.querySelector("#order");  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Submitter:", event.submitter?.textContent ?? null);    console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");  });</script>
ResultLoading…

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:

Start over, with a text box and a switchPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="tea-kit/tokens.css"><form id="order">  <p><label>Name <input name="who" value="Asha"></label></p>  <p><tea-toggle name="oat" checked>Add oat milk</tea-toggle></p>  <tea-button type="reset">Start over</tea-button></form><script type="module">  import "./tea-kit/index.js";  import "./tea-button.js";  const form = document.querySelector("#order");  form.addEventListener("reset", () => {    console.log("reset: Name is", form.elements.who.value);    setTimeout(() => console.log("then: Name is", form.elements.who.value, "and oat milk is", form.elements.oat.checked ? "on" : "off"));  });</script>
ResultLoading…
  • 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.
tea-button.js, acting by its typeJavaScript
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 called preventDefault(), 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:

Playground: what does Enter do?
An order form with tea-button, and one of three middlesPop out in the code editor (opens in a new tab)HTML
<form id="order">  <p><label>Name <input name="who" value="Asha"></label></p>  <p><label><input type="checkbox" name="lemon" checked> Lemon</label></p>  <tea-button>Place order</tea-button></form><script src="tea-button.js"></script><script>  const form = document.querySelector("#order");  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString(), "by", event.submitter?.localName ?? "the form");  });</script>
ResultLoading…
Try it yourself
One text field: the form sends itself

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.

Only lines 3 and 4 change. The tea-button.js tab is the one from the reset section.
  • 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.
A card Enter in Name, with an arrow to a card real submit button? An arrow labelled yes leads right to a card clicks it. An arrow labelled no leads down to a card one text field? From there, yes leads right to a card form sends, and no leads down to a card nothing.Enter in Namereal submit button?yesclicks itnoone text field?yesform sendsnonothing
Enter first looks for the form's first real submit button. A custom button is never one. With none, the form sends itself only when it has a single text field.
Real-life analogySaying that's all at the counter

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:

tea-button.js, finishedJavaScript
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).

Three buttons: plain, disabled, and inside a disabled fieldsetPop out in the code editor (opens in a new tab)HTML
<form id="order">  <tea-button>Place order</tea-button>  <tea-button disabled>Pay later</tea-button>  <fieldset disabled>    <legend>Gift</legend>    <tea-button type="button">Add gift wrap</tea-button>  </fieldset></form><script src="tea-button.js"></script><script>  for (const button of document.querySelectorAll("tea-button")) {    const says = (selector) => (button.matches(selector) ? "yes" : "no");    console.log(`${button.textContent}: :disabled ${says(":disabled")}, [disabled] ${says("[disabled]")}, .disabled ${button.disabled}`);  }</script>
ResultLoading…
  • 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 :disabled and [disabled], and its disabled property.
  • Place order: :disabled no, [disabled] no, .disabled false
  • Pay later: :disabled yes, [disabled] yes, .disabled true
  • Add 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.

Real-life analogyThe main switch for a room

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:

Playground: where does the native button sit?
An order form with a native button, in two placesPop out in the code editor (opens in a new tab)HTML
<form id="order">  <p><label>Name <input name="who" value="Asha"></label></p>  <p><label>Table <input name="table" value="4"></label></p>  <tea-button name="pay" value="card">Place order</tea-button></form><script src="tea-button.js"></script><script>  const form = document.querySelector("#order");  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString(), "by", event.submitter?.localName ?? "the form");  });</script>
ResultLoading…
Try it yourself
The button has no form

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.

Line 4 and the tea-button.js tab change.

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.
Two halves. Left: a crate the page holds cards form id=order and tea-button, with an arrow down to a crate shadow root that holds a card button, labelled button.form: null. Right: a crate the page holds cards form id=order, tea-button, and button, with an arrow down to a crate shadow root that holds a card slot, labelled button.form: order.form id=ordertea-buttonthe pagebuttonshadow rootbutton.form: nullform id=ordertea-buttonbuttonthe pageslotshadow rootbutton.form: order
A button in the shadow root lives in a tree of its own, with no form, so it sends nothing. A slotted button stays in the page, inside the form. The shadow root only shows it through a slot.
Real-life analogyA display phone with no SIM card

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.submitter is the button.
  • formaction and the other overrides work, and :default matches it.
  • commandfor works, 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:

The order form with the kit's buttonsPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="tea-kit/tokens.css"><form id="order">  <p><label>Name <input name="who" required></label></p>  <p><label>Table <input name="table" type="number" value="4"></label></p>  <p><tea-toggle name="oat">Add oat milk</tea-toggle></p>  <button hidden></button>  <tea-button name="pay" value="counter">Place order</tea-button>  <tea-button type="reset">Start over</tea-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, event.submitter)).toString() || "nothing");  });  form.addEventListener("reset", () => console.log("Starting over"));</script>
ResultLoading…
  • 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.
  1. Press Place order. Chrome shows "Please fill out this field." at Name, and nothing prints.
  2. Type Asha in Name and press Enter: Sent: who=Asha&table=4. The hidden button sent it.
  3. Click Add oat milk, press Tab to reach Place order, and press Space: Sent: who=Asha&table=4&oat=on&pay=counter.
  4. Press Start over: Starting over, and the form goes back to its start.

Here is the class, from tea-kit/tea-button.js:

The button's class, from tea-kit/tea-button.jsJavaScript
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:

The kit button's stylesCSS
@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 GrayText while 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 the submit event.
  • "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. :disabled finds 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

Exercise 1 · Warm-upWhat does Enter do?

Predict what Enter in Name prints, then click in Name and press Enter.

<form id="order">  <p><label>Name <input name="who" value="Asha"></label></p>  <p><label>Table <input name="table" value="4"></label></p>  <tea-button>Place order</tea-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, event.submitter)).toString() || "nothing");  });</script>
ResultLoading…

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

    Exercise 2 · Warm-upWhat does a reset bring back?

    Predict the two lines this page prints, then run it.

    <form id="order">  <p><label>Name <input name="who" value="Asha"></label></p>  <p><tea-toggle name="oat" checked>Add oat milk</tea-toggle></p>  <tea-button type="reset">Start over</tea-button></form><script type="module">  import "./tea-kit/index.js";  const form = document.querySelector("#order");  const show = (when) => console.log(`${when}: ${form.elements.who.value}, oat milk ${form.elements.oat.checked ? "on" : "off"}`);  form.elements.who.value = "Ravi";  form.elements.oat.checked = false;  show("Before");  form.addEventListener("reset", () => setTimeout(() => show("After")));  document.querySelector("tea-button").click();</script>
    ResultLoading…

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

      Exercise 3 · PracticeFix the TypeError

      Place order throws a TypeError. Fix the tea-button.js tab. What does Place order print then?

      <form id="order">  <p><label>Name <input name="who" value="Asha"></label></p>  <tea-button>Place order</tea-button></form><script src="tea-button.js"></script><script>  const form = document.querySelector("#order");  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");  });</script>
      ResultLoading…

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

        Exercise 4 · PracticeFade the button in a disabled fieldset

        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?

        <fieldset disabled>  <legend>Gift</legend>  <tea-button type="button">Add gift wrap</tea-button></fieldset><script src="tea-button.js"></script><script>  const wrap = document.querySelector("tea-button");  console.log("Opacity:", getComputedStyle(wrap).opacity);</script>
        ResultLoading…

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

          Exercise 5 · ChallengeMake Enter send the form

          Enter in Name does nothing in this form. Change the page so it sends. What does Enter in Name print then?

          <form id="order">  <p><label>Name <input name="who" value="Asha"></label></p>  <p><label>Table <input name="table" value="4"></label></p>  <tea-button>Place order</tea-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, event.submitter)).toString() || "nothing");  });</script>
          ResultLoading…

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

            Exercise 6 · ChallengeSend the button's name and value

            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?

            <form id="order">  <p><label>Name <input name="who" value="Asha"></label></p>  <tea-button name="pay" value="card">Pay by card</tea-button></form><script src="tea-button.js"></script><script>  const form = document.querySelector("#order");  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Sent:", new URLSearchParams(new FormData(form, event.submitter)).toString() || "nothing");  });</script>
            ResultLoading…

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

              Check your understanding

              The build a button quiz · 8 questionsScore: first tries count
              1. 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.

              2. Question 2 of 8Which call checks the form's fields and fires submit before it sends?

                Choose an answer to see the explanation.

              3. Question 3 of 8A custom button calls form.requestSubmit(). What is event.submitter in the submit listener?

                Choose an answer to see the explanation.

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

              5. Question 5 of 8A tea-button sits inside a <fieldset disabled>. Which selector matches it?

                Choose an answer to see the explanation.

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

              7. Question 7 of 8When does Space click a native button?

                Choose an answer to see the explanation.

              8. 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, and submit() skips the checks and the submit event.
              • event.submitter is null. The button's name and value are sent only if it lends its value while it sends.
              • Reset with form.reset(). The reset event 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:

              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.

              CompleteFrontend Clear concepts. Working examples.