Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

onhashchange — handling URL fragment changes

The onhashchange attribute on body specifies JavaScript that handles the Window object's hashchange event. It lets a page respond to same-document navigation when the URL fragment, the portion after #, changes.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

<body onhashchange="JavaScript statements">

onhashchange is an event-handler content attribute on body, not a global attribute for arbitrary HTML elements. Its value contains JavaScript statements. Although written on body, it handles the Window object's hashchange event, not an event targeting the element itself.

The event fires for same-document navigation that changes the URL fragment, such as following a fragment link or assigning a different value to location.hash. The event object is a HashChangeEvent: event.oldURL and event.newURL contain the full URLs before and after the change. Merely loading a page with an initial fragment is not a fragment change.

history.pushState() and history.replaceState() do not fire hashchange, even when they change the fragment. In the example, history.replaceState() therefore establishes the starting point without running the handler. After one click, the result should be #start -> #finish; clicking the same link again does not change the fragment.

In JavaScript, window.onhashchange exposes the same handler mechanism. Assigning a new function replaces the previous handler in that slot; window.addEventListener('hashchange', handler) lets you register independent listeners without that replacement.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>onhashchange demo</title>
</head>
<body onhashchange="document.getElementById('result').textContent = new URL(event.oldURL).hash + ' -> ' + new URL(event.newURL).hash">
  <a href="#finish">Go to #finish</a>
  <pre id="result">Ready</pre>
  <script>
    history.replaceState(null, '', '#start');
  </script>
</body>
</html>

Result

#start -> #finish

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