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 ) {
81 var str_hashchange = 'hashchange',
83 // Method / object references.
86 special = $.event.special,
88 // Does the browser support window.onhashchange? Note that IE8 running in
89 // IE7 compatibility mode reports true for 'onhashchange' in window, even
90 // though the event isn't supported, so also test document.documentMode.
91 doc_mode = doc.documentMode,
92 supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 );
94 // Get location.hash (or what you'd expect location.hash to be) sans any
95 // leading #. Thanks for making this necessary, Firefox!
96 function get_fragment( url ) {
97 url = url || location.href;
98 return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
101 // Method: jQuery.fn.hashchange
103 // Bind a handler to the window.onhashchange event or trigger all bound
104 // window.onhashchange event handlers. This behavior is consistent with
105 // jQuery's built-in event handlers.
109 // > jQuery(window).hashchange( [ handler ] );
113 // handler - (Function) Optional handler to be bound to the hashchange
114 // event. This is a "shortcut" for the more verbose form:
115 // jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
116 // all bound window.onhashchange event handlers will be triggered. This
117 // is a shortcut for the more verbose
118 // jQuery(window).trigger( 'hashchange' ). These forms are described in
119 // the <hashchange event> section.
123 // (jQuery) The initial jQuery collection of elements.
125 // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
126 // $(elem).hashchange() for triggering, like jQuery does for built-in events.
127 $.fn[ str_hashchange ] = function( fn ) {
128 return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange );
131 // Property: jQuery.fn.hashchange.delay
133 // The numeric interval (in milliseconds) at which the <hashchange event>
134 // polling loop executes. Defaults to 50.
136 // Property: jQuery.fn.hashchange.domain
138 // If you're setting document.domain in your JavaScript, and you want hash
139 // history to work in IE6/7, not only must this property be set, but you must
140 // also set document.domain BEFORE jQuery is loaded into the page. This
141 // property is only applicable if you are supporting IE6/7 (or IE8 operating
142 // in "IE7 compatibility" mode).
144 // In addition, the <jQuery.fn.hashchange.src> property must be set to the
145 // path of the included "document-domain.html" file, which can be renamed or
146 // modified if necessary (note that the document.domain specified must be the
147 // same in both your main JavaScript as well as in this file).
151 // jQuery.fn.hashchange.domain = document.domain;
153 // Property: jQuery.fn.hashchange.src
155 // If, for some reason, you need to specify an Iframe src file (for example,
156 // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can
157 // do so using this property. Note that when using this property, history
158 // won't be recorded in IE6/7 until the Iframe src file loads. This property
159 // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7
160 // compatibility" mode).
164 // jQuery.fn.hashchange.src = 'path/to/file.html';
166 $.fn[ str_hashchange ].delay = 50;
168 $.fn[ str_hashchange ].domain = null;
169 $.fn[ str_hashchange ].src = null;
172 // Event: hashchange event
174 // Fired when location.hash changes. In browsers that support it, the native
175 // HTML5 window.onhashchange event is used, otherwise a polling loop is
176 // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to
177 // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7
178 // compatibility" mode), a hidden Iframe is created to allow the back button
179 // and hash-based history to work.
181 // Usage as described in <jQuery.fn.hashchange>:
183 // > // Bind an event handler.
184 // > jQuery(window).hashchange( function(e) {
185 // > var hash = location.hash;
189 // > // Manually trigger the event handler.
190 // > jQuery(window).hashchange();
192 // A more verbose usage that allows for event namespacing:
194 // > // Bind an event handler.
195 // > jQuery(window).bind( 'hashchange', function(e) {
196 // > var hash = location.hash;
200 // > // Manually trigger the event handler.
201 // > jQuery(window).trigger( 'hashchange' );
205 // * The polling loop and Iframe are not created until at least one handler
206 // is actually bound to the 'hashchange' event.
207 // * If you need the bound handler(s) to execute immediately, in cases where
208 // a location.hash exists on page load, via bookmark or page refresh for
209 // example, use jQuery(window).hashchange() or the more verbose
210 // jQuery(window).trigger( 'hashchange' ).
211 // * The event can be bound before DOM ready, but since it won't be usable
212 // before then in IE6/7 (due to the necessary Iframe), recommended usage is
213 // to bind it inside a DOM ready handler.
215 // Override existing $.event.special.hashchange methods (allowing this plugin
216 // to be defined after jQuery BBQ in BBQ's source code).
217 special[ str_hashchange ] = $.extend( special[ str_hashchange ], {
219 // Called only when the first 'hashchange' event is bound to window.
221 // If window.onhashchange is supported natively, there's nothing to do..
222 if ( supports_onhashchange ) { return false; }
224 // Otherwise, we need to create our own. And we don't want to call this
225 // until the user binds to the event, just in case they never do, since it
226 // will create a polling loop and possibly even a hidden Iframe.
227 $( fake_onhashchange.start );
230 // Called only when the last 'hashchange' event is unbound from window.
231 teardown: function() {
232 // If window.onhashchange is supported natively, there's nothing to do..
233 if ( supports_onhashchange ) { return false; }
235 // Otherwise, we need to stop ours (if possible).
236 $( fake_onhashchange.stop );
241 // fake_onhashchange does all the work of triggering the window.onhashchange
242 // event for browsers that don't natively support it, including creating a
243 // polling loop to watch for hash changes and in IE 6/7 creating a hidden
244 // Iframe to enable back and forward.
245 fake_onhashchange = (function() {
249 // Remember the initial hash so it doesn't get triggered immediately.
250 last_hash = get_fragment(),
252 fn_retval = function( val ) { return val; },
253 history_set = fn_retval,
254 history_get = fn_retval;
256 // Start the polling loop.
257 self.start = function() {
258 timeout_id || poll();
261 // Stop the polling loop.
262 self.stop = function() {
263 timeout_id && clearTimeout( timeout_id );
264 timeout_id = undefined;
267 // This polling loop checks every $.fn.hashchange.delay milliseconds to see
268 // if location.hash has changed, and triggers the 'hashchange' event on
269 // window when necessary.
271 var hash = get_fragment(),
272 history_hash = history_get( last_hash );
274 if ( hash !== last_hash ) {
275 history_set( last_hash = hash, history_hash );
277 $(window).trigger( str_hashchange );
279 } else if ( history_hash !== last_hash ) {
280 location.href = location.href.replace( /#.*/, '' ) + history_hash;
283 timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay );
286 // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
287 // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
288 // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
289 $.browser.msie && !supports_onhashchange && (function() {
290 // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
291 // when running in "IE7 compatibility" mode.
296 // When the event is bound and polling starts in IE 6/7, create a hidden
297 // Iframe for history handling.
298 self.start = function() {
300 iframe_src = $.fn[ str_hashchange ].src;
301 iframe_src = iframe_src && iframe_src + get_fragment();
303 // Create hidden Iframe. Attempt to make Iframe as hidden as possible
304 // by using techniques from http://www.paciellogroup.com/blog/?p=604.
305 iframe = $('<iframe tabindex="-1" title="empty"/>').hide()
307 // When Iframe has completely loaded, initialize the history and
309 .one( 'load', function() {
310 iframe_src || history_set( get_fragment() );
314 // Load Iframe src if specified, otherwise nothing.
315 .attr( 'src', iframe_src || 'javascript:0' )
317 // Append Iframe after the end of the body to prevent unnecessary
318 // initial page scrolling (yes, this works).
319 .insertAfter( 'body' )[0].contentWindow;
321 // Whenever `document.title` changes, update the Iframe's title to
322 // prettify the back/next history menu entries. Since IE sometimes
323 // errors with "Unspecified error" the very first time this is set
324 // (yes, very useful) wrap this with a try/catch block.
325 doc.onpropertychange = function() {
327 if ( event.propertyName === 'title' ) {
328 iframe.document.title = doc.title;
336 // Override the "stop" method since an IE6/7 Iframe was created. Even
337 // if there are no longer any bound event handlers, the polling loop
338 // is still necessary for back/next to work at all!
339 self.stop = fn_retval;
341 // Get history by looking at the hidden Iframe's location.hash.
342 history_get = function() {
343 return get_fragment( iframe.location.href );
346 // Set a new history item by opening and then closing the Iframe
347 // document, *then* setting its location.hash. If document.domain has
348 // been set, update that as well.
349 history_set = function( hash, history_hash ) {
350 var iframe_doc = iframe.document,
351 domain = $.fn[ str_hashchange ].domain;
353 if ( hash !== history_hash ) {
354 // Update Iframe with any initial `document.title` that might be set.
355 iframe_doc.title = doc.title;
357 // Opening the Iframe's document after it has been closed is what
358 // actually adds a history entry.
361 // Set document.domain for the Iframe document as well, if necessary.
362 domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' );
366 // Update the Iframe's hash, for great justice.
367 iframe.location.hash = hash;
372 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
373 // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
374 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^