Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

hashchange — Window URL fragment changes

The hashchange event on window reports a URL fragment change during same-document navigation. It provides the previous and new URLs, but calling pushState() or replaceState() does not itself fire it.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

window.addEventListener("hashchange", handler);
window.removeEventListener("hashchange", handler);

hashchange is a Web API event on window, not part of ECMAScript itself. It reports a URL fragment change during same-document navigation, for example after assigning a different value to location.hash, following a fragment link, or moving Back/Forward between relevant history entries.

Register a function with window.addEventListener("hashchange", handler). Its HashChangeEvent has oldURL and newURL properties containing the complete URLs before and after the change. Delivery is asynchronous; read these properties when you need the URLs for that particular change.

Calling history.pushState() or history.replaceState() does not itself fire hashchange, even if it changes the fragment. Setting the identical fragment again is not a change either. Do not treat this event as notification of every URL change or as view initialization on the initial page load.

The example chooses a different fragment and listens for just one event using { once: true }. It compares fragments parsed from the event URLs, so the expected results do not depend on the page's initial URL. It requires a browser environment; the repository's Node.js version does not establish support for this API.

Examples

(() => {
  const target = location.hash === "#cktis-a" ? "#cktis-b" : "#cktis-a";

  window.addEventListener("hashchange", (event) => {
    const before = new URL(event.oldURL);
    const after = new URL(event.newURL);
    console.log(before.hash !== after.hash);
    console.log(after.hash === target);
  }, { once: true });

  location.hash = target;
})();

Result

true
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources