W3cubDocs

/jQuery Mobile

hashchange

hashchange eventversion added: 1.0

Description: Enables bookmarkable #hash history.

  • jQuery( ".selector" ).on( "hashchange", function( event ) { ... } )

The jQuery Mobile .hashchange() event handler enables very basic bookmarkable #hash history by providing a callback function bound to the window.onhashchange event. The onhashchange event fires when a window's hash changes.

In browsers that support it, the native HTML5 window.onhashchange event is used. In IE6/7 (and IE8 operating in "IE7 compatibility" mode), a hidden iframe is created to allow the back button and hash-based history to work.

This plugin extends jQuery's built-in method. If jQuery Mobile is not loaded, calling the .hashchange() method may not fail directly, as the method still exists. However, the expected behavior will not occur.

$(function() {
  // Bind an event to window.onhashchange that, when the hash changes, gets the
  // hash and adds the class "selected" to any matching nav link.
  $( window ).hashchange(function() {
    var hash = location.hash;
 
    // Set the page title based on the hash.
    document.title = "The hash is " + ( hash.replace( /^#/, "" ) || "blank" ) + ".";
 
    // Iterate over all nav links, setting the "selected" class as-appropriate.
    $( "#nav a" ).each(function() {
      var that = $( this );
      that[ that.attr( "href" ) === hash ? "addClass" : "removeClass" ]( "selected" );
    });
  });
  // Since the event is only triggered when the hash changes, we need to trigger
  // the event now, to handle the hash the page may have loaded with.
  $( window ).hashchange();
});

iFrame source: example1.html

© The jQuery Foundation and other contributors
Licensed under the MIT License.
https://api.jquerymobile.com/hashchange