HTML onhashchange Attribute

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

Definition and Usage

The onhashchange attribute is a window-level event-handler (also allowed on <body>). It runs JavaScript when the hashchange event fires — the URL fragment identifier changed (the part starting with #).

Typical triggers: clicking an in-page link like <a href="#about">, the Back/Forward buttons after hash navigations, or assigning location.hash in script. Related: onpopstate (History API) and onload (handle the initial hash).

Baseline · Widely available.

Not deprecated and not experimental. Per MDN, hashchange does not fire when the hash is changed with history.pushState() or history.replaceState(). Stable since about July 2015.

Discouraged as inline HTML.

MDN discourages HTML event handler attributes. Prefer window.addEventListener("hashchange", handler) in production; use <body onhashchange> for quick demos and learning.

HTML Syntax

syntax.html
<body onhashchange=" script">

script is JavaScript that runs when the hash changes. Equivalent JS: window.onhashchange = handler or window.addEventListener("hashchange", handler).

Attribute Values

The attribute value is always a script. Common patterns:

Value / patternDescriptionTry it
scriptAny JavaScript run when the URL hash changesTry it
onhashchange="fn()"Call a named function; read location.hashTry it
addEventListener("hashchange")Preferred modern listener — switch simple viewsTry it
oldURL / newURLHashChangeEvent fields for before/after URLsTry it

Live Preview

Click a demo link. The page hash updates and hashchange reports location.hash. (Uses #ohc-* so it stays separate from the TOC.)

Also try the browser Back button after clicking a few hashes.

Status

Waiting for hashchange… Current:

HTML Examples

Short, copy-ready snippets. Use Try It Yourself for a live editor.

Example 1 — Show the Current Hash

Update a status line whenever the fragment changes.

HTML
<body onhashchange="onHash()">
  <p>
    <a href="#home">Home</a>
    <a href="#about">About</a>
  </p>
  <p id="status">Click a link (or set location.hash).</p>

  <script>
    function onHash() {
      document.getElementById("status").textContent =
        "hashchange — now " + location.hash;
    }
  </script>
</body>
Try It Yourself

How It Works

  1. Put onhashchange on <body> (or use window.onhashchange).
  2. User changes the hash via a #… link or script.
  3. hashchange fires on the window.
  4. Read location.hash — includes the leading #.

Example 2 — Switch a Simple View

Map hashes to text panels. Also run once on load for the initial hash.

HTML
<p>
  <a href="#home">Home</a>
  <a href="#about">About</a>
</p>
<p id="panel">Choose a section.</p>

<script>
  var pages = {
    "#home": "Home panel",
    "#about": "About panel"
  };

  function render() {
    var hash = location.hash || "#home";
    document.getElementById("panel").textContent =
      pages[hash] || "Unknown hash: " + hash;
  }

  window.addEventListener("hashchange", render);
  render(); // initial hash — hashchange does not run on first load
</script>
Try It Yourself

How It Works

  1. Listen with addEventListener for maintainable code.
  2. Map hashes to UI — tabs, sections, or lightweight “routes”.
  3. Call render() on load — hashchange does not fire for the first paint.
  4. Default empty hash if you want a home view when there is no fragment.

Example 3 — HashChangeEvent oldURL / newURL

The event object exposes the previous and next full URLs.

HTML
<p>
  <a href="#one">#one</a>
  <a href="#two">#two</a>
</p>
<p id="log">Change the hash to see oldURL → newURL.</p>

<script>
  window.addEventListener("hashchange", function (event) {
    document.getElementById("log").textContent =
      "From: " + event.oldURL + " → To: " + event.newURL;
  });
</script>
Try It Yourself

How It Works

  1. Handler receives a HashChangeEvent.
  2. event.oldURL — full URL before the change.
  3. event.newURL — full URL after the change.
  4. Still use location.hash when you only need the fragment string.

Edge Cases & Pitfalls

Most “hashchange never ran” bugs are expecting it on first load or after pushState.

load

No fire on first load

If the user opens page.html#about, call your render function once on load (or immediately in a script). hashchange only runs on later changes.

history

pushState / replaceState

Per MDN, changing the hash via history.pushState() or replaceState() does not fire hashchange. Prefer onpopstate for History API apps.

target

Window / body only

This is not an input event. Put the handler on window or <body onhashchange>, not on a button or field.

scroll

Same-page anchors scroll

A matching id on the page still scrolls into view. Use unique demo hashes (or preventDefault on clicks) when you only want routing, not scrolling.

spa

Hash routing vs History API

Hash routes work without a server rewrite. Clean URLs usually use pushState + popstate instead of # fragments.

Browser Support

onhashchange is a window / body event-handler in the browser. It is not a Node.js, Deno, or Bun API.

✓ Baseline · Widely available

onhashchange

Widely available since about July 2015. Chrome, Firefox, Safari, Edge, and Opera support hashchange on window.

97% Global support (approx.)
Google Chrome All modern
Full support
Mozilla Firefox All modern
Full support
Apple Safari All modern
Full support
Microsoft Edge All modern
Full support
Opera All modern
Full support
Samsung Internet Modern
Full support
Internet Explorer 8+
Supported
onhashchange Widely supported

Bottom line: Safe to use for hash-based UI. Prefer addEventListener('hashchange') in apps, sync once on load, and use popstate for pushState routing.

Key Takeaways

  • Role: the URL #fragment changed.
  • Window / body handler — not for form controls.
  • No initial fire — sync once on load for the starting hash.
  • Not for pushState — use popstate with the History API.

One line: onhashchange means the # part of the URL changed — listen on window, and render once on load too.

Frequently Asked Questions

It is a window-level event-handler attribute (also allowed on body). When the URL fragment identifier (the part starting with #) changes, the hashchange event fires and the JavaScript in onhashchange runs.
On the window (window.onhashchange) or as an attribute on body (and historically frameset). It is not for input or button elements.
No. It only fires when the hash changes after load. Call your sync/render function once on load to handle an initial hash already in the URL.
Per MDN, hashchange does not fire when the hash is modified with history.pushState() or history.replaceState(). Those navigations relate more to popstate.
hashchange is specifically for location.hash changes. popstate fires for session history navigations involving pushState/replaceState (and some back/forward cases). Modern History API apps often use popstate instead of hash routing.
No. The hashchange event and onhashchange handler are standard and Baseline widely available since about July 2015. Inline HTML handlers are discouraged in production in favor of addEventListener.

Next: oninput

Run JavaScript when a control’s value changes while the user types.

oninput tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful