1 // Script: jQuery hashchange event
3 // *Version: 1.3, Last updated: 7/21/2010*
5 // Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
6 // GitHub - http://github.com/cowboy/jquery-hashchange/
7 // Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
8 // (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped)
12 // Copyright (c) 2010 "Cowboy" Ben Alman,
13 // Dual licensed under the MIT and GPL licenses.
14 // http://benalman.com/about/license/
18 // These working examples, complete with fully commented code, illustrate a few
19 // ways in which this plugin can be used.
21 // hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
22 // document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/
24 // About: Support and Testing
26 // Information about what version or versions of jQuery this plugin has been
27 // tested with, what browsers it has been tested in, and where the unit tests
28 // reside (so you can test it yourself).
30 // jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2
31 // Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5,
32 // Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5.
33 // Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/
35 // About: Known issues
37 // While this jQuery hashchange event implementation is quite stable and
38 // robust, there are a few unfortunate browser bugs surrounding expected
39 // hashchange event-based behaviors, independent of any JavaScript
40 // window.onhashchange abstraction. See the following examples for more
43 // Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
44 // Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
45 // WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
46 // Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
48 // Also note that should a browser natively support the window.onhashchange
49 // event, but not report that it does, the fallback polling loop will be used.
51 // About: Release History
53 // 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more
54 // "removable" for mobile-only development. Added IE6/7 document.title
55 // support. Attempted to make Iframe as hidden as possible by using
56 // techniques from http://www.paciellogroup.com/blog/?p=604. Added
57 // support for the "shortcut" format $(window).hashchange( fn ) and
58 // $(window).hashchange() like jQuery provides for built-in events.
59 // Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and
60 // lowered its default value to 50. Added <jQuery.fn.hashchange.domain>
61 // and <jQuery.fn.hashchange.src> properties plus document-domain.html
62 // file to address access denied issues when setting document.domain in
64 // 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin
65 // from a page on another domain would cause an error in Safari 4. Also,
66 // IE6/7 Iframe is now inserted after the body (this actually works),
67 // which prevents the page from scrolling when the event is first bound.
68 // Event can also now be bound before DOM ready, but it won't be usable
69 // before then in IE6/7.
70 // 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
71 // where browser version is incorrectly reported as 8.0, despite
72 // inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
73 // 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
74 // window.onhashchange functionality into a separate plugin for users
75 // who want just the basic event & back button support, without all the
76 // extra awesomeness that BBQ provides. This plugin will be included as
77 // part of jQuery BBQ, but also be available separately.
79 (function($,window,undefined){
80 '$:nomunge'; // Used by YUI compressor.
83 var str_hashchange = 'hashchange',
85 // Method / object references.
88 special = $.event.special,
90 // Does the browser support window.onhashchange? Note that IE8 running in
91 // IE7 compatibility mode reports true for 'onhashchange' in window, even
92 // though the event isn't supported, so also test document.documentMode.
93 doc_mode = doc.documentMode,
94 supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 );
96 // Get location.hash (or what you'd expect location.hash to be) sans any
97 // leading #. Thanks for making this necessary, Firefox!
98 function get_fragment( url ) {
99 url = url || location.href;
100 return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
103 // Method: jQuery.fn.hashchange
105 // Bind a handler to the window.onhashchange event or trigger all bound
106 // window.onhashchange event handlers. This behavior is consistent with
107 // jQuery's built-in event handlers.
111 // > jQuery(window).hashchange( [ handler ] );
115 // handler - (Function) Optional handler to be bound to the hashchange
116 // event. This is a "shortcut" for the more verbose form:
117 // jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
118 // all bound window.onhashchange event handlers will be triggered. This
119 // is a shortcut for the more verbose
120 // jQuery(window).trigger( 'hashchange' ). These forms are described in
121 // the <hashchange event> section.
125 // (jQuery) The initial jQuery collection of elements.
127 // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
128 // $(elem).hashchange() for triggering, like jQuery does for built-in events.
129 $.fn[ str_hashchange ] = function( fn ) {
130 return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange );
133 // Property: jQuery.fn.hashchange.delay
135 // The numeric interval (in milliseconds) at which the <hashchange event>
136 // polling loop executes. Defaults to 50.
138 // Property: jQuery.fn.hashchange.domain
140 // If you're setting document.domain in your JavaScript, and you want hash
141 // history to work in IE6/7, not only must this property be set, but you must
142 // also set document.domain BEFORE jQuery is loaded into the page. This
143 // property is only applicable if you are supporting IE6/7 (or IE8 operating
144 // in "IE7 compatibility" mode).
146 // In addition, the <jQuery.fn.hashchange.src> property must be set to the
147 // path of the included "document-domain.html" file, which can be renamed or
148 // modified if necessary (note that the document.domain specified must be the
149 // same in both your main JavaScript as well as in this file).
153 // jQuery.fn.hashchange.domain = document.domain;
155 // Property: jQuery.fn.hashchange.src
157 // If, for some reason, you need to specify an Iframe src file (for example,
158 // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can
159 // do so using this property. Note that when using this property, history
160 // won't be recorded in IE6/7 until the Iframe src file loads. This property
161 // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7
162 // compatibility" mode).
166 // jQuery.fn.hashchange.src = 'path/to/file.html';
168 $.fn[ str_hashchange ].delay = 50;
170 $.fn[ str_hashchange ].domain = null;
171 $.fn[ str_hashchange ].src = null;
174 // Event: hashchange event
176 // Fired when location.hash changes. In browsers that support it, the native
177 // HTML5 window.onhashchange event is used, otherwise a polling loop is
178 // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to
179 // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7
180 // compatibility" mode), a hidden Iframe is created to allow the back button
181 // and hash-based history to work.
183 // Usage as described in <jQuery.fn.hashchange>:
185 // > // Bind an event handler.
186 // > jQuery(window).hashchange( function(e) {
187 // > var hash = location.hash;
191 // > // Manually trigger the event handler.
192 // > jQuery(window).hashchange();
194 // A more verbose usage that allows for event namespacing:
196 // > // Bind an event handler.
197 // > jQuery(window).bind( 'hashchange', function(e) {
198 // > var hash = location.hash;
202 // > // Manually trigger the event handler.
203 // > jQuery(window).trigger( 'hashchange' );
207 // * The polling loop and Iframe are not created until at least one handler
208 // is actually bound to the 'hashchange' event.
209 // * If you need the bound handler(s) to execute immediately, in cases where
210 // a location.hash exists on page load, via bookmark or page refresh for
211 // example, use jQuery(window).hashchange() or the more verbose
212 // jQuery(window).trigger( 'hashchange' ).
213 // * The event can be bound before DOM ready, but since it won't be usable
214 // before then in IE6/7 (due to the necessary Iframe), recommended usage is
215 // to bind it inside a DOM ready handler.
217 // Override existing $.event.special.hashchange methods (allowing this plugin
218 // to be defined after jQuery BBQ in BBQ's source code).
219 special[ str_hashchange ] = $.extend( special[ str_hashchange ], {
221 // Called only when the first 'hashchange' event is bound to window.
223 // If window.onhashchange is supported natively, there's nothing to do..
224 if ( supports_onhashchange ) { return false; }
226 // Otherwise, we need to create our own. And we don't want to call this
227 // until the user binds to the event, just in case they never do, since it
228 // will create a polling loop and possibly even a hidden Iframe.
229 $( fake_onhashchange.start );
232 // Called only when the last 'hashchange' event is unbound from window.
233 teardown: function() {
234 // If window.onhashchange is supported natively, there's nothing to do..
235 if ( supports_onhashchange ) { return false; }
237 // Otherwise, we need to stop ours (if possible).
238 $( fake_onhashchange.stop );
243 // fake_onhashchange does all the work of triggering the window.onhashchange
244 // event for browsers that don't natively support it, including creating a
245 // polling loop to watch for hash changes and in IE 6/7 creating a hidden
246 // Iframe to enable back and forward.
247 fake_onhashchange = (function(){
251 // Remember the initial hash so it doesn't get triggered immediately.
252 last_hash = get_fragment(),
254 fn_retval = function(val){ return val; },
255 history_set = fn_retval,
256 history_get = fn_retval;
258 // Start the polling loop.
259 self.start = function() {
260 timeout_id || poll();
263 // Stop the polling loop.
264 self.stop = function() {
265 timeout_id && clearTimeout( timeout_id );
266 timeout_id = undefined;
269 // This polling loop checks every $.fn.hashchange.delay milliseconds to see
270 // if location.hash has changed, and triggers the 'hashchange' event on
271 // window when necessary.
273 var hash = get_fragment(),
274 history_hash = history_get( last_hash );
276 if ( hash !== last_hash ) {
277 history_set( last_hash = hash, history_hash );
279 $(window).trigger( str_hashchange );
281 } else if ( history_hash !== last_hash ) {
282 location.href = location.href.replace( /#.*/, '' ) + history_hash;
285 timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay );
288 // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
289 // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
290 // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
291 $.browser.msie && !supports_onhashchange && (function(){
292 // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
293 // when running in "IE7 compatibility" mode.
298 // When the event is bound and polling starts in IE 6/7, create a hidden
299 // Iframe for history handling.
300 self.start = function(){
302 iframe_src = $.fn[ str_hashchange ].src;
303 iframe_src = iframe_src && iframe_src + get_fragment();
305 // Create hidden Iframe. Attempt to make Iframe as hidden as possible
306 // by using techniques from http://www.paciellogroup.com/blog/?p=604.
307 iframe = $('<iframe tabindex="-1" title="empty"/>').hide()
309 // When Iframe has completely loaded, initialize the history and
311 .one( 'load', function(){
312 iframe_src || history_set( get_fragment() );
316 // Load Iframe src if specified, otherwise nothing.
317 .attr( 'src', iframe_src || 'javascript:0' )
319 // Append Iframe after the end of the body to prevent unnecessary
320 // initial page scrolling (yes, this works).
321 .insertAfter( 'body' )[0].contentWindow;
323 // Whenever `document.title` changes, update the Iframe's title to
324 // prettify the back/next history menu entries. Since IE sometimes
325 // errors with "Unspecified error" the very first time this is set
326 // (yes, very useful) wrap this with a try/catch block.
327 doc.onpropertychange = function(){
329 if ( event.propertyName === 'title' ) {
330 iframe.document.title = doc.title;
338 // Override the "stop" method since an IE6/7 Iframe was created. Even
339 // if there are no longer any bound event handlers, the polling loop
340 // is still necessary for back/next to work at all!
341 self.stop = fn_retval;
343 // Get history by looking at the hidden Iframe's location.hash.
344 history_get = function() {
345 return get_fragment( iframe.location.href );
348 // Set a new history item by opening and then closing the Iframe
349 // document, *then* setting its location.hash. If document.domain has
350 // been set, update that as well.
351 history_set = function( hash, history_hash ) {
352 var iframe_doc = iframe.document,
353 domain = $.fn[ str_hashchange ].domain;
355 if ( hash !== history_hash ) {
356 // Update Iframe with any initial `document.title` that might be set.
357 iframe_doc.title = doc.title;
359 // Opening the Iframe's document after it has been closed is what
360 // actually adds a history entry.
363 // Set document.domain for the Iframe document as well, if necessary.
364 domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' );
368 // Update the Iframe's hash, for great justice.
369 iframe.location.hash = hash;
374 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
375 // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
376 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^