Skip to content

Instantly share code, notes, and snippets.

@LoonyPandora
Created March 13, 2013 23:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LoonyPandora/5157532 to your computer and use it in GitHub Desktop.
Save LoonyPandora/5157532 to your computer and use it in GitHub Desktop.
How to bind to the JS "hashchange" event.
// Watches for changes in the URL hashbang and updates the #content pane accordingly
// Also updates the hash when we click on a link
function initHashChange() {
// 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 = window.location.hash.replace( /^#!\//, '' );
if (hash == '') { return; }
$('#content').children().hide();
$('#' + hash + '-panel').show();
// Highlights the item in the list, deselects all other routes
$('.showpanel').removeClass('selected');
$('#' + hash).addClass('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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment