Skip to content
jshacks.dev
Browser

JavaScript toggle Event: When It Fires and How to Use It

When the JavaScript toggle event fires for details, popovers and dialogs, how beforetoggle and newState work, and how to lazy-load content with it.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Google Chrome, Redis and RabbitMQ logos.

HTML now has several elements that open and close on their own: the <details> disclosure, popovers made with the popover attribute, and, in current browsers, the <dialog> element in its newer forms. Each of them changes state without any script, and each of them reports the change through the same toggle event. That makes it the single hook for "this thing just opened or closed" across the platform's built-in disclosure widgets: load content the first time a section opens, save which accordion panels are expanded, focus the first field of a popover, or update an aria-expanded attribute on a custom trigger. This post explains how the JavaScript toggle event works: on which elements it fires and what it carries, how beforetoggle differs and when it is cancelable, how to read oldState and newState, how events are queued and when they fire relative to rendering, how to build exclusive accordions with name, how to lazy-load content, how to persist open state, and how to test it. It is defined in the HTML Standard, documented on MDN, and supported in all current browsers.

On <details>

When the user opens or closes a <details> element, or script changes its open attribute, the element fires toggle. The event does not bubble for <details>, so listen on the element itself, though you can use capture on an ancestor to delegate. Read the state from details.open.

basic.jsJavaScript
document.body.innerHTML = `
  <details id="faq">
    <summary>What is a toggle?</summary>
    <p>An event for disclosure widgets.</p>
  </details>
`;

const details = document.querySelector("#faq");

details.addEventListener("toggle", () => {
  console.log(details.open ? "opened" : "closed");
});

details.open = true;
await new Promise((resolve) => setTimeout(resolve));
details.open = false;
Text
opened
closed

The event is asynchronous: setting open queues a task that fires the event later, so the handler runs after the code that made the change. If you set open twice in the same task, the event fires once, with the final state. In the example, the await gives the first event time to run. A handler registered after the attribute change but before the task runs still sees the event, which is occasionally useful and often surprising.

beforetoggle and the state properties

Popovers and dialogs fire two events. beforetoggle fires just before the change and, for opening, is cancelable. toggle fires after it. Both are ToggleEvent objects with oldState and newState, which are "closed" or "open".

popover.jsJavaScript
document.body.innerHTML = '<div id="menu" popover>Menu</div>';
const menu = document.querySelector("#menu");

menu.addEventListener("beforetoggle", (event) => {
  console.log("before", event.oldState, "->", event.newState);
});

menu.addEventListener("toggle", (event) => {
  console.log("after", event.oldState, "->", event.newState);
});

menu.showPopover();
await new Promise((resolve) => setTimeout(resolve));
menu.hidePopover();
Text
before closed -> open
after closed -> open
before open -> closed
after open -> closed

Use newState rather than reading the element's state, since by the time an asynchronous toggle handler runs, the state may have changed again, and the event tells you which change it describes. beforetoggle is the place to fill the content before it appears, or to cancel an opening with event.preventDefault(), for example if the user lacks permission or the data is not ready. Closing cannot be canceled, since the user expects Escape and outside clicks to work.

cancel.jsJavaScript
let allowed = false;

menu.addEventListener("beforetoggle", (event) => {
  if (event.newState === "open" && !allowed) {
    event.preventDefault();
    console.log("blocked");
  }
});

try {
  menu.showPopover();
} catch (error) {
  console.log(error.name);
}
console.log(menu.matches(":popover-open"));
Text
blocked
false

The showPopover() call does not throw when the event is canceled in current browsers, and the popover simply does not open, so check :popover-open if you need to know.

What else fires it

The toggle event also fires on <dialog> in recent browsers, where beforetoggle and toggle report opening and closing, including when a dialog is closed with close() or the Escape key. For the older close and cancel events of dialogs, those remain, and toggle is an additional, uniform signal. The popover attribute works on any element, and its events have the same shape, so one function can handle disclosure widgets of all three kinds.

uniform.jsJavaScript
document.addEventListener(
  "toggle",
  (event) => {
    const el = event.target;
    const open = el.matches("details") ? el.open : el.matches(":popover-open, dialog[open]");
    console.log(el.tagName.toLowerCase(), open);
  },
  true,
);
Text
details true
div false

The true argument makes the listener run in the capture phase, which is how you receive events that do not bubble, from the document root.

Lazy loading content

A common use is to defer expensive content until the section is first opened: a comments list, a data table, an embedded video or a heavy widget.

lazy.jsJavaScript
const comments = document.querySelector("details.comments");
let loaded = false;

comments.addEventListener("toggle", async () => {
  if (!comments.open || loaded) return;
  loaded = true;

  const response = await fetch("/api/comments?post=42");
  const items = await response.json();

  const list = document.createElement("ul");
  list.append(
    ...items.map((item) => {
      const li = document.createElement("li");
      li.textContent = item.text;
      return li;
    }),
  );
  comments.append(list);
  console.log("loaded", items.length);
});
Text
loaded 3

The loaded flag keeps the fetch from running on each open, and setting it before the request prevents a second fetch if the user toggles quickly. Show a loading indicator in the section while waiting, and handle errors by resetting the flag so the next open can retry. Search engines and users who print the page will not see lazy content, so keep important text in the markup.

Exclusive accordions

A group of <details> elements with the same name attribute behaves as an exclusive accordion: opening one closes the others, with no script. Each closing fires its own toggle event, so state-tracking code still works.

accordion.htmlHTML
<details name="faq" open><summary>One</summary><p>First answer</p></details>
<details name="faq"><summary>Two</summary><p>Second answer</p></details>
<details name="faq"><summary>Three</summary><p>Third answer</p></details>
Text
(opening Two closes One; both fire toggle events)

Before the name attribute, accordions needed a toggle handler that closed siblings, which looked like this, and it still works for browsers that lack the attribute.

exclusive.jsJavaScript
document.addEventListener(
  "toggle",
  (event) => {
    const el = event.target;
    if (!el.matches("details[data-group]") || !el.open) return;

    document.querySelectorAll(`details[data-group="${el.dataset.group}"]`).forEach((other) => {
      if (other !== el) other.open = false;
    });
  },
  true,
);
Text
(opening one panel of a data-group closes the others)

Persisting open state

Remember which sections the user expanded, for example in a documentation sidebar, by saving the state in localStorage and restoring it on load.

persist.jsJavaScript
const key = "sidebar-open";
const saved = new Set(JSON.parse(localStorage.getItem(key) ?? "[]"));

document.querySelectorAll("details[id]").forEach((details) => {
  details.open = saved.has(details.id);

  details.addEventListener("toggle", () => {
    details.open ? saved.add(details.id) : saved.delete(details.id);
    localStorage.setItem(key, JSON.stringify([...saved]));
  });
});

console.log(saved.size);
Text
2

Setting open during restoration fires toggle events too, which write back the same values, so the loop is harmless, though you may prefer to attach the listeners after setting the state. Wrap storage access in a try block for private browsing modes where it throws.

Syncing a custom trigger

A button that controls a popover should expose its state to assistive technology. With popovertarget, the browser handles that for you. For a custom trigger built in script, sync aria-expanded from toggle.

aria.jsJavaScript
const trigger = document.querySelector("#trigger");
const popover = document.querySelector("#panel");

popover.addEventListener("toggle", (event) => {
  trigger.setAttribute("aria-expanded", String(event.newState === "open"));
});

trigger.addEventListener("click", () => popover.togglePopover());
Text
(aria-expanded follows the real state, whether the popover was closed by a click, Escape or outside press)

Using the event instead of setting the attribute in the click handler keeps the two in agreement when the browser closes the popover by itself, which is the case a click handler cannot see.

Testing

Real toggle events come from the browser, in a task after the change. In a test, wait for the event with a promise, or dispatch new ToggleEvent("toggle", { oldState: "closed", newState: "open" }) to test a handler on its own. Playwright can click a <summary> and assert on the resulting open property and the loaded content.

test.jsJavaScript
const details = document.createElement("details");
document.body.append(details);

const opened = new Promise((resolve) => details.addEventListener("toggle", resolve, { once: true }));
details.open = true;
await opened;

console.log(details.open);
Text
true

Pitfalls

Expecting the event to be synchronous. Expecting <details> toggles to bubble. Relying on the element's state instead of newState in an asynchronous handler. Loading content on every open. Trying to cancel a close in beforetoggle. Using toggle for lazy content that search engines need. Forgetting that restoring state fires events. And handling accordion exclusivity in script where the name attribute does it for free.

Accessibility

Disclosure widgets are only as accessible as the state they announce. A native <summary> inside <details> already exposes its expanded state to screen readers, and a popover opened from a popovertarget button gets the same treatment, so prefer the native elements over a custom div and a script. When you do add behavior in a toggle handler, keep it from fighting the native semantics: do not move focus out of a <details> that the user just opened by keyboard, do not close a popover that holds focus without returning focus to its trigger, and do not hide content with display: none while a transition is still announcing it. For content that loads on open, announce the arrival through a live region, because a list that appears inside an expanded section is not announced by the expansion itself.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.