Back

The Hash-Change Event

About

hashchange is an event which fires whenever the hash portion of a URL has changed.

From the WHATWG specification1, this event is formally described as "[...] fired when navigating to a session history entry whose URL differs from that of the previous one only in the fragment identifier."

Binding

It is defined on window and, a function fn can be bound in any of the following ways2.

  1. window.onhashchange = fn;
  2. <body onhashchange="fn();">
  3. window.addEventListener("hashchange", fn, false);

Demo

The following links change the hash portion of the URL. For example, the link with text "Change hash to A" has an href attrubute equal to #A.

The following items show the properties passed into the hashchange event when it fires.

Source Code

The source code for this demo is displayed below. The trim function removes all the text in a string up to the last forward-slash. This is useful so that we can display only the final part of the URL.

window.onhashchange = function(evt) {
    document
        .getElementById("hashchangeTime")
        .innerText = new Date().toTimeString(); 
    document
        .getElementById("hashchangeNew")
        .innerText = trim(evt.newURL)
    document
        .getElementById("hashchangeOld")
        .innerText = trim(evt.oldURL);
    document
        .getElementById("hashchangeHash")
        .innerText = location.hash;
};
  
function trim(s) {
    return "..." + s.match(/\/[^/]+$/)[0];
}
        

References

  1. http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#event-hashchange
  2. https://developer.mozilla.org/en/DOM/window.onhashchange