-
-
Save quirkey/189397 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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