HTML Buttons <button>

HTML Living Standard

A button starts an action such as revealing information or submitting a form. The browser supplies built-in keyboard behavior.

On this page

What does a button provide?

A button is a control the user can activate. The contents supply the label. A normal button can receive keyboard focus; the disabled attribute makes a button unavailable. A custom action needs an instruction such as JavaScript, which the next example adds.

How to try it In index.html, replace the content between <body> and </body> with this example. Save the file and reload it in the browser.

<button type="button">Add to cart</button>
<button type="button" disabled>Out of stock</button>

What to expect Press Tab to reach the first button. The disabled button is skipped. The first button is ready for a custom action.

Trigger an action with type="button"

Use type="button" for a custom action that needs JavaScript, especially inside a form. The browser generates a click when a user activates the button with a mouse or with Enter or Space while it has focus. The example listens for that event and toggles an element’s hidden state.

How to try it In index.html, replace the content between <body> and </body> with this example. Save the file and reload it in the browser.

<button type="button" id="toggle" aria-expanded="false" aria-controls="hours">Show hours</button>
<p id="hours" hidden>Open 9:00 AM to 6:00 PM.</p>
<script>
  const button = document.querySelector("#toggle");
  const hours = document.querySelector("#hours");
  button.addEventListener("click", () => {
    hours.hidden = !hours.hidden;
    button.textContent = hours.hidden ? "Show hours" : "Hide hours";
    button.setAttribute("aria-expanded", String(!hours.hidden));
  });
</script>

What to expect The first click shows the hours and the second hides them. aria-expanded mirrors the state for assistive tools.

Submit a form with type="submit"

A submit button asks the browser to validate and submit its form. For a regular button inside a form, leaving out type generally makes it a submit button. Write the type explicitly to make the intended behavior clear.

How to try it In index.html, replace the content between <body> and </body> with this example. Save the file and reload it in the browser.

<form method="get">
  <label for="query">Search term</label>
  <input id="query" name="q" required>
  <button type="submit">Search</button>
</form>

What to expect The browser blocks an empty submission. Enter pen and submit in a standalone HTML file to see ?q=pen in the URL. A search service would still need to handle the query.

Official references