Skip to content

Instantly share code, notes, and snippets.

@brandonaaron
Forked from cowboy/gist:189255
Created September 18, 2009 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brandonaaron/189260 to your computer and use it in GitHub Desktop.
Save brandonaaron/189260 to your computer and use it in GitHub Desktop.
// requires nightly version of jQuery b/c it uses the add special event hook
// more about special event hooks: http://brandonaaron.net/blog/2009/06/4/jquery-edge-new-special-event-hooks
(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() {
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