Events

onhashchange

The URL fragment changes through fragment navigation. Window event handler, exposed through the body element in HTML; register on window rather than on an arbitrary element. Event interface: HashChangeEvent. For the described native event: bubbles: no; cancelable: no. oldURL and newURL are available; pushState and replaceState do not fire hashchange by themselves. Example: Click the fragment link. The event listener is registered with addEventListener(), which avoids inline script handlers and supports multiple listeners. Inline handlers require a CSP that permits them; do not insert untrusted code into handler attributes.

Formal Syntax & Structure

html syntaxhtml
<body onhashchange="handleEvent(event)">  window.addEventListener("hashchange", event => { /* handle event */ });

Parameters & Attributes

NameTypeDescription
onhashchangeJavaScript handler bodyOptional HTML event-handler code; the example uses a registered listener instead. Not a Boolean attribute.
eventHashChangeEventEvent object delivered to the addEventListener callback; event.type is "hashchange". Inspect target, currentTarget, bubbles and cancelable as appropriate.

Working Example

Example Snippethtml
<p>Window event monitor</p><p>  <a href="#section">Change fragment</a></p><p id="section">Section</p><p role="status" id="log">Waiting for hashchange</p><script>  const target = window;  const log = document.getElementById("log");  target.addEventListener("hashchange", event => {    log.textContent = String(event.newURL);  });</script>
HTML Reference