# .togglePopover()

> The `.togglePopover()` JS method toggles a popover element between shown and hidden states.

## How do I toggle a popover with JavaScript?

The method that shows a hidden popover or hides a shown one. Optionally takes a boolean argument to force a specific state and returns `true` if the popover is shown after the call.

- Topic: Object on Page
- Type: method
- Browser support: Chrome 114+, Chrome Android 114+, Edge 114+, Firefox 125+, Firefox Android 125+, Safari 17+, Safari iOS 17+

## Example

Wrong:

```js
let isOpen = false;
button.addEventListener('click', () => {
  isOpen = !isOpen;
  isOpen ? menu.showPopover() : menu.hidePopover();
});
```

Right:

```js
button.addEventListener('click', () => menu.togglePopover());
menu.addEventListener('toggle', (e) => {
  button.setAttribute('aria-expanded', String(e.newState === 'open'));
});
```

The popover's own state is the source of truth, so Esc and outside clicks keep `aria-expanded` correct.

## Common mistakes

- Keeping a separate `isOpen` variable that drifts when the user closes the popover with Esc.

## Key points

- A plain toggle button uses `popovertarget`, not a click handler with `togglePopover()`.
- The boolean result of `togglePopover()` is used to know the new state, not a separate flag.
- When toggled from JS, the trigger's `aria-expanded` is updated in the `toggle` event.

## Interview questions

### What does togglePopover return?

It returns `true` if the popover is open after the call and `false` if it is closed.

### Can togglePopover only open or only close a popover?

Yes. Pass `true` to only open it or `false` to only close it, like `togglePopover(true)`.

## Related cards

- [.showPopover()](https://wonderium.dev/js/show-popover.md)
- [.hidePopover()](https://wonderium.dev/js/hide-popover.md)
- [\[popovertarget\]](https://wonderium.dev/html/popovertarget.md)
- [\[popover\]](https://wonderium.dev/html/popover.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/toggle-popover
- Last updated: 2026-11-25
