References

Beginner-friendly references for web development, with live, editable examples.

The HTML onpopstate event

Event All modern browsers Updated
Quick answer

The HTML onpopstate attribute runs JavaScript when the active history entry changes (e.g. Back/Forward). It is an inline handler for the popstate event; in modern code prefer addEventListener('popstate', …).

Overview

The onpopstate event attribute runs JavaScript on history navigation. In JavaScript the event itself is named popstate — drop the on prefix when you call addEventListener.

It is a window- or document-level event rather than one tied to a particular element, so it is handled on window or document. These events cover the page lifecycle, navigation, network status, messaging and similar global concerns.

You can wire this up with the inline onpopstate HTML attribute, but the modern, recommended approach is element.addEventListener('popstate', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.

Syntax

<element onpopstate="handler()">…</element>

element.addEventListener('popstate', handler);

Best practices

  • Prefer element.addEventListener('popstate', handler) over the inline onpopstate attribute — it separates behavior from markup and allows multiple handlers.
  • Attach these on window (or document) with addEventListener rather than as <body> attributes.
  • Keep these handlers fast — they run at moments that affect the whole page.
  • Remove listeners you no longer need to avoid leaks in long-lived pages.

Frequently asked questions

What is the onpopstate event?
It runs JavaScript on history navigation. In JavaScript the event is named popstate.
Where do I attach this event?
On window or document — these are global events, not tied to a single element.
Can I use it as a body attribute?
You can, but window.addEventListener is preferred — it keeps behavior out of the markup and allows multiple handlers.
Should I use the onpopstate attribute or addEventListener?
Prefer addEventListener('popstate', …) in JavaScript. The inline onpopstate attribute works but mixes behavior into the markup and allows only one handler per element.