Skip to content

Instantly share code, notes, and snippets.

@quirkey
Forked from brandonaaron/hashchange.js
Created September 19, 2009 03:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quirkey/189397 to your computer and use it in GitHub Desktop.
Save quirkey/189397 to your computer and use it in GitHub Desktop.
(function( $ ) {
$.event.special.hashchange = {
setup: function( data, namespaces) {
if ( 'onhashchange' in window ) {
// sweet, native support... short-circuit
return false;
}
// onhashchange is not natively supported ... work around it :(
fakeHashChange();
},
add: function( handler, data, namespaces ) {
return function() {
arguments[0].hash = getHash();
handler.apply( this, arguments );
};
},
teardown: function( namespaces ) {
if ( 'onhashchange' in window ) {
// sweet, native support... short-circuit
return false;
}
// onhashchange is not natively supported ... work around it :(
unfakeHashChange();
}
};
var prevHash = getHash(), interval;
function fakeHashChange() {
interval = setInterval( function() {
var currHash = getHash();
if ( currHash !== prevHash ) {
prevHash = currHash;
$( window ).trigger( 'hashchange' );
}
}, 300 );
}
function unfakeHashChange() {
clearInterval( interval );
}
function getHash() {
var loc = document.location;
return loc.hash ? loc.href.replace( /^.*\#/, '' ) : '';
}
})( jQuery );
// usage/test
$(function(){
$( window ).bind( 'hashchange', function( e ) {
console.log( 'hashchange', e.hash );
} );
var arr = [ 'foo', 'bar', 'baz' ];
(function loopy() {
arr.length && setTimeout(function() {
var hash = '#' + arr.shift();
console.log( 'setting hash to', hash );
document.location.hash = hash
loopy();
}, 1000);
})();
$( window ).trigger( 'hashchange' );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment