jQuery special events
Custom hashchange event
http://benalman.com/news/2010/03/jquery-special-events/
HTML
<h1>
<a href="http://benalman.com/news/2010/03/jquery-special-events/" target="_top">jQuery special events</a>
» Custom hashchange event
</h1>
<p class="intro">(click links)</p>
<div id="test">
<a href="#foo">foo</a>
<a href="#bar">bar</a>
<a href="#baz">baz</a>
</div>
<div id="log"></div>
CSS
body { font-family: Arial, Helvetica, sans-serif; font-size: 0.8em; }
h1 { font-weight: 700; font-family: "Gill Sans", "Gill Sans MT", Arial, Helvetica, sans-serif; }
h1, a { color: #913D00; }
a:hover { color: #FF7F00; }
h1 { font-size: 120%; margin-bottom: 0.6em; }
.intro { font-style: italic; margin-top: 0.5em; }
#test {
margin-top: 1em;
}
#log {
margin-top: 1em;
}
JavaScript
$(function(){
function log(){
$('#log').append([].join.call(arguments,', ')+'<br/>');
};
// Bind an event to window.onhashchange.
$(window).bind( 'hashchange', function(event){
log( 'event.fragment: "' + event.fragment + '"' );
});
// 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).trigger( 'hashchange' );
});
//////////////////////////////////////////////////
// THE FOLLOWING CODE IS TAKEN FROM THE EXAMPLE //
//////////////////////////////////////////////////
(function($){
// Store the initial location.hash so that the event isn't triggered when
// the page is first loaded.
var last_hash = location.hash,
// An id with which the polling loop can be canceled.
timeout_id;
// Special event definition.
$.event.special.hashchange = {
setup: function() {
// If the event is supported natively, return false so that jQuery
// will bind to the event using DOM methods instead of using the
// polling loop.
if ( 'onhashchange' in window ) { return false; }
// Start the polling loop if it's not already running.
start();
},
teardown: function() {
// If the event is supported natively, return false so that jQuery
// will bind to the event using DOM methods instead of using the
// polling loop.
if ( 'onhashchange' in window ) { return false; }
// Stop the polling loop. Since this event is only evern bound to
// the `window` object, multiple-element tracking is unnecessary.
stop();
},
add: function( handleObj ) {
// Save a reference to the bound event handler.
var old_handler = handleObj.handler;
// This function will now be called when the event is triggered,
// instead of the bound event handler.
handleObj.handler =...