2 * jQuery Mobile Framework 1.1.1 1981b3f5ec22675ae47df8f0bdf9622e7780e90e
3 * http://jquerymobile.com
5 * Copyright 2012 jQuery Foundation and other contributors
6 * Dual licensed under the MIT or GPL Version 2 licenses.
7 * http://jquery.org/license
10 (function ( root, doc, factory ) {
11 if ( typeof define === "function" && define.amd ) {
12 // AMD. Register as an anonymous module.
13 define( [ "jquery" ], function ( $ ) {
14 factory( $, root, doc );
19 factory( root.jQuery, root, doc );
21 }( this, document, function ( jQuery, window, document, undefined ) {
24 // This plugin is an experiment for abstracting away the touch and mouse
25 // events so that developers don't have to worry about which method of input
26 // the device their document is loaded on supports.
28 // The idea here is to allow the developer to register listeners for the
29 // basic mouse events, such as mousedown, mousemove, mouseup, and click,
30 // and the plugin will take care of registering the correct listeners
31 // behind the scenes to invoke the listener at the fastest possible time
32 // for that device, while still retaining the order of event firing in
33 // the traditional mouse environment, should multiple handlers be registered
34 // on the same element for different events.
36 // The current version exposes the following virtual events to jQuery bind methods:
37 // "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel"
39 (function( $, window, document, undefined ) {
41 var dataPropertyName = "virtualMouseBindings",
42 touchTargetPropertyName = "virtualTouchID",
43 virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ),
44 touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ),
45 mouseHookProps = $.event.mouseHooks ? $.event.mouseHooks.props : [],
46 mouseEventProps = $.event.props.concat( mouseHookProps ),
47 activeDocHandlers = {},
53 blockMouseTriggers = false,
54 blockTouchTriggers = false,
55 eventCaptureSupported = "addEventListener" in document,
56 $document = $( document ),
61 moveDistanceThreshold: 10,
62 clickDistanceThreshold: 10,
63 resetTimerDuration: 1500
66 function getNativeEvent( event ) {
68 while ( event && typeof event.originalEvent !== "undefined" ) {
69 event = event.originalEvent;
74 function createVirtualEvent( event, eventType ) {
77 oe, props, ne, prop, ct, touch, i, j;
79 event = $.Event(event);
80 event.type = eventType;
82 oe = event.originalEvent;
83 props = $.event.props;
85 // addresses separation of $.event.props in to $.event.mouseHook.props and Issue 3280
86 // https://github.com/jquery/jquery-mobile/issues/3280
87 if ( t.search( /^(mouse|click)/ ) > -1 ) {
88 props = mouseEventProps;
91 // copy original event properties over to the new event
92 // this would happen if we could call $.event.fix instead of $.Event
93 // but we don't have a way to force an event to be fixed multiple times
95 for ( i = props.length, prop; i; ) {
97 event[ prop ] = oe[ prop ];
101 // make sure that if the mouse and click virtual events are generated
102 // without a .which one is defined
103 if ( t.search(/mouse(down|up)|click/) > -1 && !event.which ){
107 if ( t.search(/^touch/) !== -1 ) {
108 ne = getNativeEvent( oe );
110 ct = ne.changedTouches;
111 touch = ( t && t.length ) ? t[0] : ( (ct && ct.length) ? ct[ 0 ] : undefined );
114 for ( j = 0, len = touchEventProps.length; j < len; j++){
115 prop = touchEventProps[ j ];
116 event[ prop ] = touch[ prop ];
124 function getVirtualBindingFlags( element ) {
131 b = $.data( element, dataPropertyName );
135 flags[ k ] = flags.hasVirtualBinding = true;
138 element = element.parentNode;
143 function getClosestElementWithVirtualBinding( element, eventType ) {
147 b = $.data( element, dataPropertyName );
149 if ( b && ( !eventType || b[ eventType ] ) ) {
152 element = element.parentNode;
157 function enableTouchBindings() {
158 blockTouchTriggers = false;
161 function disableTouchBindings() {
162 blockTouchTriggers = true;
165 function enableMouseBindings() {
167 clickBlockList.length = 0;
168 blockMouseTriggers = false;
170 // When mouse bindings are enabled, our
171 // touch bindings are disabled.
172 disableTouchBindings();
175 function disableMouseBindings() {
176 // When mouse bindings are disabled, our
177 // touch bindings are enabled.
178 enableTouchBindings();
181 function startResetTimer() {
183 resetTimerID = setTimeout(function(){
185 enableMouseBindings();
186 }, $.vmouse.resetTimerDuration );
189 function clearResetTimer() {
191 clearTimeout( resetTimerID );
196 function triggerVirtualEvent( eventType, event, flags ) {
199 if ( ( flags && flags[ eventType ] ) ||
200 ( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) {
202 ve = createVirtualEvent( event, eventType );
204 $( event.target).trigger( ve );
210 function mouseEventCallback( event ) {
211 var touchID = $.data(event.target, touchTargetPropertyName);
213 if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ){
214 var ve = triggerVirtualEvent( "v" + event.type, event );
216 if ( ve.isDefaultPrevented() ) {
217 event.preventDefault();
219 if ( ve.isPropagationStopped() ) {
220 event.stopPropagation();
222 if ( ve.isImmediatePropagationStopped() ) {
223 event.stopImmediatePropagation();
229 function handleTouchStart( event ) {
231 var touches = getNativeEvent( event ).touches,
234 if ( touches && touches.length === 1 ) {
236 target = event.target;
237 flags = getVirtualBindingFlags( target );
239 if ( flags.hasVirtualBinding ) {
241 lastTouchID = nextTouchID++;
242 $.data( target, touchTargetPropertyName, lastTouchID );
246 disableMouseBindings();
249 var t = getNativeEvent( event ).touches[ 0 ];
253 triggerVirtualEvent( "vmouseover", event, flags );
254 triggerVirtualEvent( "vmousedown", event, flags );
259 function handleScroll( event ) {
260 if ( blockTouchTriggers ) {
265 triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) );
272 function handleTouchMove( event ) {
273 if ( blockTouchTriggers ) {
277 var t = getNativeEvent( event ).touches[ 0 ],
278 didCancel = didScroll,
279 moveThreshold = $.vmouse.moveDistanceThreshold;
280 didScroll = didScroll ||
281 ( Math.abs(t.pageX - startX) > moveThreshold ||
282 Math.abs(t.pageY - startY) > moveThreshold ),
283 flags = getVirtualBindingFlags( event.target );
285 if ( didScroll && !didCancel ) {
286 triggerVirtualEvent( "vmousecancel", event, flags );
289 triggerVirtualEvent( "vmousemove", event, flags );
293 function handleTouchEnd( event ) {
294 if ( blockTouchTriggers ) {
298 disableTouchBindings();
300 var flags = getVirtualBindingFlags( event.target ),
302 triggerVirtualEvent( "vmouseup", event, flags );
305 var ve = triggerVirtualEvent( "vclick", event, flags );
306 if ( ve && ve.isDefaultPrevented() ) {
307 // The target of the mouse events that follow the touchend
308 // event don't necessarily match the target used during the
309 // touch. This means we need to rely on coordinates for blocking
310 // any click that is generated.
311 t = getNativeEvent( event ).changedTouches[ 0 ];
312 clickBlockList.push({
313 touchID: lastTouchID,
318 // Prevent any mouse events that follow from triggering
319 // virtual event notifications.
320 blockMouseTriggers = true;
323 triggerVirtualEvent( "vmouseout", event, flags);
329 function hasVirtualBindings( ele ) {
330 var bindings = $.data( ele, dataPropertyName ),
334 for ( k in bindings ) {
335 if ( bindings[ k ] ) {
343 function dummyMouseHandler(){}
345 function getSpecialEventObject( eventType ) {
346 var realType = eventType.substr( 1 );
349 setup: function( data, namespace ) {
350 // If this is the first virtual mouse binding for this element,
351 // add a bindings object to its data.
353 if ( !hasVirtualBindings( this ) ) {
354 $.data( this, dataPropertyName, {});
357 // If setup is called, we know it is the first binding for this
358 // eventType, so initialize the count for the eventType to zero.
359 var bindings = $.data( this, dataPropertyName );
360 bindings[ eventType ] = true;
362 // If this is the first virtual mouse event for this type,
363 // register a global handler on the document.
365 activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1;
367 if ( activeDocHandlers[ eventType ] === 1 ) {
368 $document.bind( realType, mouseEventCallback );
371 // Some browsers, like Opera Mini, won't dispatch mouse/click events
372 // for elements unless they actually have handlers registered on them.
373 // To get around this, we register dummy handlers on the elements.
375 $( this ).bind( realType, dummyMouseHandler );
377 // For now, if event capture is not supported, we rely on mouse handlers.
378 if ( eventCaptureSupported ) {
379 // If this is the first virtual mouse binding for the document,
380 // register our touchstart handler on the document.
382 activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1;
384 if (activeDocHandlers[ "touchstart" ] === 1) {
385 $document.bind( "touchstart", handleTouchStart )
386 .bind( "touchend", handleTouchEnd )
388 // On touch platforms, touching the screen and then dragging your finger
389 // causes the window content to scroll after some distance threshold is
390 // exceeded. On these platforms, a scroll prevents a click event from being
391 // dispatched, and on some platforms, even the touchend is suppressed. To
392 // mimic the suppression of the click event, we need to watch for a scroll
393 // event. Unfortunately, some platforms like iOS don't dispatch scroll
394 // events until *AFTER* the user lifts their finger (touchend). This means
395 // we need to watch both scroll and touchmove events to figure out whether
396 // or not a scroll happenens before the touchend event is fired.
398 .bind( "touchmove", handleTouchMove )
399 .bind( "scroll", handleScroll );
404 teardown: function( data, namespace ) {
405 // If this is the last virtual binding for this eventType,
406 // remove its global handler from the document.
408 --activeDocHandlers[ eventType ];
410 if ( !activeDocHandlers[ eventType ] ) {
411 $document.unbind( realType, mouseEventCallback );
414 if ( eventCaptureSupported ) {
415 // If this is the last virtual mouse binding in existence,
416 // remove our document touchstart listener.
418 --activeDocHandlers[ "touchstart" ];
420 if ( !activeDocHandlers[ "touchstart" ] ) {
421 $document.unbind( "touchstart", handleTouchStart )
422 .unbind( "touchmove", handleTouchMove )
423 .unbind( "touchend", handleTouchEnd )
424 .unbind( "scroll", handleScroll );
428 var $this = $( this ),
429 bindings = $.data( this, dataPropertyName );
431 // teardown may be called when an element was
432 // removed from the DOM. If this is the case,
433 // jQuery core may have already stripped the element
434 // of any data bindings so we need to check it before
437 bindings[ eventType ] = false;
440 // Unregister the dummy event handler.
442 $this.unbind( realType, dummyMouseHandler );
444 // If this is the last virtual mouse binding on the
445 // element, remove the binding data from the element.
447 if ( !hasVirtualBindings( this ) ) {
448 $this.removeData( dataPropertyName );
454 // Expose our custom events to the jQuery bind/unbind mechanism.
456 for ( var i = 0; i < virtualEventNames.length; i++ ){
457 $.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] );
460 // Add a capture click handler to block clicks.
461 // Note that we require event capture support for this so if the device
462 // doesn't support it, we punt for now and rely solely on mouse events.
463 if ( eventCaptureSupported ) {
464 document.addEventListener( "click", function( e ){
465 var cnt = clickBlockList.length,
467 x, y, ele, i, o, touchID;
472 threshold = $.vmouse.clickDistanceThreshold;
474 // The idea here is to run through the clickBlockList to see if
475 // the current click event is in the proximity of one of our
476 // vclick events that had preventDefault() called on it. If we find
477 // one, then we block the click.
479 // Why do we have to rely on proximity?
481 // Because the target of the touch event that triggered the vclick
482 // can be different from the target of the click event synthesized
483 // by the browser. The target of a mouse/click event that is syntehsized
484 // from a touch event seems to be implementation specific. For example,
485 // some browsers will fire mouse/click events for a link that is near
486 // a touch event, even though the target of the touchstart/touchend event
487 // says the user touched outside the link. Also, it seems that with most
488 // browsers, the target of the mouse/click event is not calculated until the
489 // time it is dispatched, so if you replace an element that you touched
490 // with another element, the target of the mouse/click will be the new
491 // element underneath that point.
493 // Aside from proximity, we also check to see if the target and any
494 // of its ancestors were the ones that blocked a click. This is necessary
495 // because of the strange mouse/click target calculation done in the
496 // Android 2.1 browser, where if you click on an element, and there is a
497 // mouse/click handler on one of its ancestors, the target will be the
498 // innermost child of the touched element, even if that child is no where
499 // near the point of touch.
504 for ( i = 0; i < cnt; i++ ) {
505 o = clickBlockList[ i ];
508 if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) ||
509 $.data( ele, touchTargetPropertyName ) === o.touchID ) {
510 // XXX: We may want to consider removing matches from the block list
511 // instead of waiting for the reset timer to fire.
517 ele = ele.parentNode;
522 })( jQuery, window, document );
526 // Script: jQuery hashchange event
528 // *Version: 1.3, Last updated: 7/21/2010*
530 // Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
531 // GitHub - http://github.com/cowboy/jquery-hashchange/
532 // Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
533 // (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped)
537 // Copyright (c) 2010 "Cowboy" Ben Alman,
538 // Dual licensed under the MIT and GPL licenses.
539 // http://benalman.com/about/license/
543 // These working examples, complete with fully commented code, illustrate a few
544 // ways in which this plugin can be used.
546 // hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
547 // document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/
549 // About: Support and Testing
551 // Information about what version or versions of jQuery this plugin has been
552 // tested with, what browsers it has been tested in, and where the unit tests
553 // reside (so you can test it yourself).
555 // jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2
556 // Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5,
557 // Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5.
558 // Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/
560 // About: Known issues
562 // While this jQuery hashchange event implementation is quite stable and
563 // robust, there are a few unfortunate browser bugs surrounding expected
564 // hashchange event-based behaviors, independent of any JavaScript
565 // window.onhashchange abstraction. See the following examples for more
568 // Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
569 // Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
570 // WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
571 // Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
573 // Also note that should a browser natively support the window.onhashchange
574 // event, but not report that it does, the fallback polling loop will be used.
576 // About: Release History
578 // 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more
579 // "removable" for mobile-only development. Added IE6/7 document.title
580 // support. Attempted to make Iframe as hidden as possible by using
581 // techniques from http://www.paciellogroup.com/blog/?p=604. Added
582 // support for the "shortcut" format $(window).hashchange( fn ) and
583 // $(window).hashchange() like jQuery provides for built-in events.
584 // Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and
585 // lowered its default value to 50. Added <jQuery.fn.hashchange.domain>
586 // and <jQuery.fn.hashchange.src> properties plus document-domain.html
587 // file to address access denied issues when setting document.domain in
589 // 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin
590 // from a page on another domain would cause an error in Safari 4. Also,
591 // IE6/7 Iframe is now inserted after the body (this actually works),
592 // which prevents the page from scrolling when the event is first bound.
593 // Event can also now be bound before DOM ready, but it won't be usable
594 // before then in IE6/7.
595 // 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
596 // where browser version is incorrectly reported as 8.0, despite
597 // inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
598 // 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
599 // window.onhashchange functionality into a separate plugin for users
600 // who want just the basic event & back button support, without all the
601 // extra awesomeness that BBQ provides. This plugin will be included as
602 // part of jQuery BBQ, but also be available separately.
604 (function($,window,undefined){
606 var str_hashchange = 'hashchange',
608 // Method / object references.
611 special = $.event.special,
613 // Does the browser support window.onhashchange? Note that IE8 running in
614 // IE7 compatibility mode reports true for 'onhashchange' in window, even
615 // though the event isn't supported, so also test document.documentMode.
616 doc_mode = doc.documentMode,
617 supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 );
619 // Get location.hash (or what you'd expect location.hash to be) sans any
620 // leading #. Thanks for making this necessary, Firefox!
621 function get_fragment( url ) {
622 url = url || location.href;
623 return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
626 // Method: jQuery.fn.hashchange
628 // Bind a handler to the window.onhashchange event or trigger all bound
629 // window.onhashchange event handlers. This behavior is consistent with
630 // jQuery's built-in event handlers.
634 // > jQuery(window).hashchange( [ handler ] );
638 // handler - (Function) Optional handler to be bound to the hashchange
639 // event. This is a "shortcut" for the more verbose form:
640 // jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
641 // all bound window.onhashchange event handlers will be triggered. This
642 // is a shortcut for the more verbose
643 // jQuery(window).trigger( 'hashchange' ). These forms are described in
644 // the <hashchange event> section.
648 // (jQuery) The initial jQuery collection of elements.
650 // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
651 // $(elem).hashchange() for triggering, like jQuery does for built-in events.
652 $.fn[ str_hashchange ] = function( fn ) {
653 return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange );
656 // Property: jQuery.fn.hashchange.delay
658 // The numeric interval (in milliseconds) at which the <hashchange event>
659 // polling loop executes. Defaults to 50.
661 // Property: jQuery.fn.hashchange.domain
663 // If you're setting document.domain in your JavaScript, and you want hash
664 // history to work in IE6/7, not only must this property be set, but you must
665 // also set document.domain BEFORE jQuery is loaded into the page. This
666 // property is only applicable if you are supporting IE6/7 (or IE8 operating
667 // in "IE7 compatibility" mode).
669 // In addition, the <jQuery.fn.hashchange.src> property must be set to the
670 // path of the included "document-domain.html" file, which can be renamed or
671 // modified if necessary (note that the document.domain specified must be the
672 // same in both your main JavaScript as well as in this file).
676 // jQuery.fn.hashchange.domain = document.domain;
678 // Property: jQuery.fn.hashchange.src
680 // If, for some reason, you need to specify an Iframe src file (for example,
681 // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can
682 // do so using this property. Note that when using this property, history
683 // won't be recorded in IE6/7 until the Iframe src file loads. This property
684 // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7
685 // compatibility" mode).
689 // jQuery.fn.hashchange.src = 'path/to/file.html';
691 $.fn[ str_hashchange ].delay = 50;
693 $.fn[ str_hashchange ].domain = null;
694 $.fn[ str_hashchange ].src = null;
697 // Event: hashchange event
699 // Fired when location.hash changes. In browsers that support it, the native
700 // HTML5 window.onhashchange event is used, otherwise a polling loop is
701 // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to
702 // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7
703 // compatibility" mode), a hidden Iframe is created to allow the back button
704 // and hash-based history to work.
706 // Usage as described in <jQuery.fn.hashchange>:
708 // > // Bind an event handler.
709 // > jQuery(window).hashchange( function(e) {
710 // > var hash = location.hash;
714 // > // Manually trigger the event handler.
715 // > jQuery(window).hashchange();
717 // A more verbose usage that allows for event namespacing:
719 // > // Bind an event handler.
720 // > jQuery(window).bind( 'hashchange', function(e) {
721 // > var hash = location.hash;
725 // > // Manually trigger the event handler.
726 // > jQuery(window).trigger( 'hashchange' );
730 // * The polling loop and Iframe are not created until at least one handler
731 // is actually bound to the 'hashchange' event.
732 // * If you need the bound handler(s) to execute immediately, in cases where
733 // a location.hash exists on page load, via bookmark or page refresh for
734 // example, use jQuery(window).hashchange() or the more verbose
735 // jQuery(window).trigger( 'hashchange' ).
736 // * The event can be bound before DOM ready, but since it won't be usable
737 // before then in IE6/7 (due to the necessary Iframe), recommended usage is
738 // to bind it inside a DOM ready handler.
740 // Override existing $.event.special.hashchange methods (allowing this plugin
741 // to be defined after jQuery BBQ in BBQ's source code).
742 special[ str_hashchange ] = $.extend( special[ str_hashchange ], {
744 // Called only when the first 'hashchange' event is bound to window.
746 // If window.onhashchange is supported natively, there's nothing to do..
747 if ( supports_onhashchange ) { return false; }
749 // Otherwise, we need to create our own. And we don't want to call this
750 // until the user binds to the event, just in case they never do, since it
751 // will create a polling loop and possibly even a hidden Iframe.
752 $( fake_onhashchange.start );
755 // Called only when the last 'hashchange' event is unbound from window.
756 teardown: function() {
757 // If window.onhashchange is supported natively, there's nothing to do..
758 if ( supports_onhashchange ) { return false; }
760 // Otherwise, we need to stop ours (if possible).
761 $( fake_onhashchange.stop );
766 // fake_onhashchange does all the work of triggering the window.onhashchange
767 // event for browsers that don't natively support it, including creating a
768 // polling loop to watch for hash changes and in IE 6/7 creating a hidden
769 // Iframe to enable back and forward.
770 fake_onhashchange = (function(){
774 // Remember the initial hash so it doesn't get triggered immediately.
775 last_hash = get_fragment(),
777 fn_retval = function(val){ return val; },
778 history_set = fn_retval,
779 history_get = fn_retval;
781 // Start the polling loop.
782 self.start = function() {
783 timeout_id || poll();
786 // Stop the polling loop.
787 self.stop = function() {
788 timeout_id && clearTimeout( timeout_id );
789 timeout_id = undefined;
792 // This polling loop checks every $.fn.hashchange.delay milliseconds to see
793 // if location.hash has changed, and triggers the 'hashchange' event on
794 // window when necessary.
796 var hash = get_fragment(),
797 history_hash = history_get( last_hash );
799 if ( hash !== last_hash ) {
800 history_set( last_hash = hash, history_hash );
802 $(window).trigger( str_hashchange );
804 } else if ( history_hash !== last_hash ) {
805 location.href = location.href.replace( /#.*/, '' ) + history_hash;
808 timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay );
811 // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
812 // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
813 // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
814 $.browser.msie && !supports_onhashchange && (function(){
815 // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
816 // when running in "IE7 compatibility" mode.
821 // When the event is bound and polling starts in IE 6/7, create a hidden
822 // Iframe for history handling.
823 self.start = function(){
825 iframe_src = $.fn[ str_hashchange ].src;
826 iframe_src = iframe_src && iframe_src + get_fragment();
828 // Create hidden Iframe. Attempt to make Iframe as hidden as possible
829 // by using techniques from http://www.paciellogroup.com/blog/?p=604.
830 iframe = $('<iframe tabindex="-1" title="empty"/>').hide()
832 // When Iframe has completely loaded, initialize the history and
834 .one( 'load', function(){
835 iframe_src || history_set( get_fragment() );
839 // Load Iframe src if specified, otherwise nothing.
840 .attr( 'src', iframe_src || 'javascript:0' )
842 // Append Iframe after the end of the body to prevent unnecessary
843 // initial page scrolling (yes, this works).
844 .insertAfter( 'body' )[0].contentWindow;
846 // Whenever `document.title` changes, update the Iframe's title to
847 // prettify the back/next history menu entries. Since IE sometimes
848 // errors with "Unspecified error" the very first time this is set
849 // (yes, very useful) wrap this with a try/catch block.
850 doc.onpropertychange = function(){
852 if ( event.propertyName === 'title' ) {
853 iframe.document.title = doc.title;
861 // Override the "stop" method since an IE6/7 Iframe was created. Even
862 // if there are no longer any bound event handlers, the polling loop
863 // is still necessary for back/next to work at all!
864 self.stop = fn_retval;
866 // Get history by looking at the hidden Iframe's location.hash.
867 history_get = function() {
868 return get_fragment( iframe.location.href );
871 // Set a new history item by opening and then closing the Iframe
872 // document, *then* setting its location.hash. If document.domain has
873 // been set, update that as well.
874 history_set = function( hash, history_hash ) {
875 var iframe_doc = iframe.document,
876 domain = $.fn[ str_hashchange ].domain;
878 if ( hash !== history_hash ) {
879 // Update Iframe with any initial `document.title` that might be set.
880 iframe_doc.title = doc.title;
882 // Opening the Iframe's document after it has been closed is what
883 // actually adds a history entry.
886 // Set document.domain for the Iframe document as well, if necessary.
887 domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' );
891 // Update the Iframe's hash, for great justice.
892 iframe.location.hash = hash;
897 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
898 // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
899 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
907 * jQuery UI Widget @VERSION
909 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
910 * Dual licensed under the MIT or GPL Version 2 licenses.
911 * http://jquery.org/license
913 * http://docs.jquery.com/UI/Widget
916 (function( $, undefined ) {
920 var _cleanData = $.cleanData;
921 $.cleanData = function( elems ) {
922 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
923 $( elem ).triggerHandler( "remove" );
928 var _remove = $.fn.remove;
929 $.fn.remove = function( selector, keepData ) {
930 return this.each(function() {
932 if ( !selector || $.filter( selector, [ this ] ).length ) {
933 $( "*", this ).add( [ this ] ).each(function() {
934 $( this ).triggerHandler( "remove" );
938 return _remove.call( $(this), selector, keepData );
943 $.widget = function( name, base, prototype ) {
944 var namespace = name.split( "." )[ 0 ],
946 name = name.split( "." )[ 1 ];
947 fullName = namespace + "-" + name;
954 // create selector for plugin
955 $.expr[ ":" ][ fullName ] = function( elem ) {
956 return !!$.data( elem, name );
959 $[ namespace ] = $[ namespace ] || {};
960 $[ namespace ][ name ] = function( options, element ) {
961 // allow instantiation without initializing for simple inheritance
962 if ( arguments.length ) {
963 this._createWidget( options, element );
967 var basePrototype = new base();
968 // we need to make the options hash a property directly on the new instance
969 // otherwise we'll modify the options hash on the prototype that we're
971 // $.each( basePrototype, function( key, val ) {
972 // if ( $.isPlainObject(val) ) {
973 // basePrototype[ key ] = $.extend( {}, val );
976 basePrototype.options = $.extend( true, {}, basePrototype.options );
977 $[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
978 namespace: namespace,
980 widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
981 widgetBaseClass: fullName
984 $.widget.bridge( name, $[ namespace ][ name ] );
987 $.widget.bridge = function( name, object ) {
988 $.fn[ name ] = function( options ) {
989 var isMethodCall = typeof options === "string",
990 args = Array.prototype.slice.call( arguments, 1 ),
993 // allow multiple hashes to be passed on init
994 options = !isMethodCall && args.length ?
995 $.extend.apply( null, [ true, options ].concat(args) ) :
998 // prevent calls to internal methods
999 if ( isMethodCall && options.charAt( 0 ) === "_" ) {
1003 if ( isMethodCall ) {
1004 this.each(function() {
1005 var instance = $.data( this, name );
1007 throw "cannot call methods on " + name + " prior to initialization; " +
1008 "attempted to call method '" + options + "'";
1010 if ( !$.isFunction( instance[options] ) ) {
1011 throw "no such method '" + options + "' for " + name + " widget instance";
1013 var methodValue = instance[ options ].apply( instance, args );
1014 if ( methodValue !== instance && methodValue !== undefined ) {
1015 returnValue = methodValue;
1020 this.each(function() {
1021 var instance = $.data( this, name );
1023 instance.option( options || {} )._init();
1025 $.data( this, name, new object( options, this ) );
1034 $.Widget = function( options, element ) {
1035 // allow instantiation without initializing for simple inheritance
1036 if ( arguments.length ) {
1037 this._createWidget( options, element );
1041 $.Widget.prototype = {
1042 widgetName: "widget",
1043 widgetEventPrefix: "",
1047 _createWidget: function( options, element ) {
1048 // $.widget.bridge stores the plugin instance, but we do it anyway
1049 // so that it's stored even before the _create function runs
1050 $.data( element, this.widgetName, this );
1051 this.element = $( element );
1052 this.options = $.extend( true, {},
1054 this._getCreateOptions(),
1058 this.element.bind( "remove." + this.widgetName, function() {
1063 this._trigger( "create" );
1066 _getCreateOptions: function() {
1069 options = $.metadata.get( element )[ this.widgetName ];
1073 _create: function() {},
1074 _init: function() {},
1076 destroy: function() {
1078 .unbind( "." + this.widgetName )
1079 .removeData( this.widgetName );
1081 .unbind( "." + this.widgetName )
1082 .removeAttr( "aria-disabled" )
1084 this.widgetBaseClass + "-disabled " +
1085 "ui-state-disabled" );
1088 widget: function() {
1089 return this.element;
1092 option: function( key, value ) {
1095 if ( arguments.length === 0 ) {
1096 // don't return a reference to the internal hash
1097 return $.extend( {}, this.options );
1100 if (typeof key === "string" ) {
1101 if ( value === undefined ) {
1102 return this.options[ key ];
1105 options[ key ] = value;
1108 this._setOptions( options );
1112 _setOptions: function( options ) {
1114 $.each( options, function( key, value ) {
1115 self._setOption( key, value );
1120 _setOption: function( key, value ) {
1121 this.options[ key ] = value;
1123 if ( key === "disabled" ) {
1125 [ value ? "addClass" : "removeClass"](
1126 this.widgetBaseClass + "-disabled" + " " +
1127 "ui-state-disabled" )
1128 .attr( "aria-disabled", value );
1134 enable: function() {
1135 return this._setOption( "disabled", false );
1137 disable: function() {
1138 return this._setOption( "disabled", true );
1141 _trigger: function( type, event, data ) {
1142 var callback = this.options[ type ];
1144 event = $.Event( event );
1145 event.type = ( type === this.widgetEventPrefix ?
1147 this.widgetEventPrefix + type ).toLowerCase();
1150 // copy original event properties over to the new event
1151 // this would happen if we could call $.event.fix instead of $.Event
1152 // but we don't have a way to force an event to be fixed multiple times
1153 if ( event.originalEvent ) {
1154 for ( var i = $.event.props.length, prop; i; ) {
1155 prop = $.event.props[ --i ];
1156 event[ prop ] = event.originalEvent[ prop ];
1160 this.element.trigger( event, data );
1162 return !( $.isFunction(callback) &&
1163 callback.call( this.element[0], event, data ) === false ||
1164 event.isDefaultPrevented() );
1170 (function( $, undefined ) {
1172 $.widget( "mobile.widget", {
1173 // decorate the parent _createWidget to trigger `widgetinit` for users
1174 // who wish to do post post `widgetcreate` alterations/additions
1176 // TODO create a pull request for jquery ui to trigger this event
1177 // in the original _createWidget
1178 _createWidget: function() {
1179 $.Widget.prototype._createWidget.apply( this, arguments );
1180 this._trigger( 'init' );
1183 _getCreateOptions: function() {
1185 var elem = this.element,
1188 $.each( this.options, function( option ) {
1190 var value = elem.jqmData( option.replace( /[A-Z]/g, function( c ) {
1191 return "-" + c.toLowerCase();
1195 if ( value !== undefined ) {
1196 options[ option ] = value;
1203 enhanceWithin: function( target, useKeepNative ) {
1204 this.enhance( $( this.options.initSelector, $( target )), useKeepNative );
1207 enhance: function( targets, useKeepNative ) {
1208 var page, keepNative, $widgetElements = $( targets ), self = this;
1210 // if ignoreContentEnabled is set to true the framework should
1211 // only enhance the selected elements when they do NOT have a
1212 // parent with the data-namespace-ignore attribute
1213 $widgetElements = $.mobile.enhanceable( $widgetElements );
1215 if ( useKeepNative && $widgetElements.length ) {
1216 // TODO remove dependency on the page widget for the keepNative.
1217 // Currently the keepNative value is defined on the page prototype so
1218 // the method is as well
1219 page = $.mobile.closestPageData( $widgetElements );
1220 keepNative = (page && page.keepNativeSelector()) || "";
1222 $widgetElements = $widgetElements.not( keepNative );
1225 $widgetElements[ this.widgetName ]();
1228 raise: function( msg ) {
1229 throw "Widget [" + this.widgetName + "]: " + msg;
1235 (function( $, window, undefined ) {
1237 var nsNormalizeDict = {};
1239 // jQuery.mobile configurable options
1240 $.mobile = $.extend( {}, {
1242 // Version of the jQuery Mobile Framework
1245 // Namespace used framework-wide for data-attrs. Default is no namespace
1248 // Define the url parameter used for referencing widget-generated sub-pages.
1249 // Translates to to example.html&ui-page=subpageIdentifier
1250 // hash segment before &ui-page= is used to make Ajax request
1251 subPageUrlKey: "ui-page",
1253 // Class assigned to page currently in view, and during transitions
1254 activePageClass: "ui-page-active",
1256 // Class used for "active" button state, from CSS framework
1257 activeBtnClass: "ui-btn-active",
1259 // Class used for "focus" form element state, from CSS framework
1260 focusClass: "ui-focus",
1262 // Automatically handle clicks and form submissions through Ajax, when same-domain
1265 // Automatically load and show pages based on location.hash
1266 hashListeningEnabled: true,
1268 // disable to prevent jquery from bothering with links
1269 linkBindingEnabled: true,
1271 // Set default page transition - 'none' for no transitions
1272 defaultPageTransition: "fade",
1274 // Set maximum window width for transitions to apply - 'false' for no limit
1275 maxTransitionWidth: false,
1277 // Minimum scroll distance that will be remembered when returning to a page
1280 // DEPRECATED: the following property is no longer in use, but defined until 2.0 to prevent conflicts
1281 touchOverflowEnabled: false,
1283 // Set default dialog transition - 'none' for no transitions
1284 defaultDialogTransition: "pop",
1286 // Show loading message during Ajax requests
1287 // if false, message will not appear, but loading classes will still be toggled on html el
1288 loadingMessage: "loading",
1290 // Error response message - appears when an Ajax page request fails
1291 pageLoadErrorMessage: "Error Loading Page",
1293 // Should the text be visble in the loading message?
1294 loadingMessageTextVisible: false,
1296 // When the text is visible, what theme does the loading box use?
1297 loadingMessageTheme: "a",
1299 // For error messages, which theme does the box uses?
1300 pageLoadErrorMessageTheme: "e",
1302 //automatically initialize the DOM when it's ready
1303 autoInitializePage: true,
1305 pushStateEnabled: true,
1307 // allows users to opt in to ignoring content by marking a parent element as
1309 ignoreContentEnabled: false,
1311 // turn of binding to the native orientationchange due to android orientation behavior
1312 orientationChangeEnabled: true,
1318 // TODO might be useful upstream in jquery itself ?
1325 COMMAND_LEFT: 91, // COMMAND
1336 MENU: 93, // COMMAND_RIGHT
1338 NUMPAD_DECIMAL: 110,
1341 NUMPAD_MULTIPLY: 106,
1342 NUMPAD_SUBTRACT: 109,
1351 WINDOWS: 91 // COMMAND
1354 // Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value
1355 silentScroll: function( ypos ) {
1356 if ( $.type( ypos ) !== "number" ) {
1357 ypos = $.mobile.defaultHomeScroll;
1360 // prevent scrollstart and scrollstop events
1361 $.event.special.scrollstart.enabled = false;
1363 setTimeout(function() {
1364 window.scrollTo( 0, ypos );
1365 $( document ).trigger( "silentscroll", { x: 0, y: ypos });
1368 setTimeout(function() {
1369 $.event.special.scrollstart.enabled = true;
1373 // Expose our cache for testing purposes.
1374 nsNormalizeDict: nsNormalizeDict,
1376 // Take a data attribute property, prepend the namespace
1377 // and then camel case the attribute string. Add the result
1378 // to our nsNormalizeDict so we don't have to do this again.
1379 nsNormalize: function( prop ) {
1384 return nsNormalizeDict[ prop ] || ( nsNormalizeDict[ prop ] = $.camelCase( $.mobile.ns + prop ) );
1387 // Find the closest parent with a theme class on it. Note that
1388 // we are not using $.fn.closest() on purpose here because this
1389 // method gets called quite a bit and we need it to be as fast
1391 getInheritedTheme: function( el, defaultTheme ) {
1394 re = /ui-(bar|body|overlay)-([a-z])\b/,
1398 c = e.className || "";
1399 if ( c && ( m = re.exec( c ) ) && ( ltr = m[ 2 ] ) ) {
1400 // We found a parent with a theme class
1401 // on it so bail from this loop.
1408 // Return the theme letter we found, if none, return the
1409 // specified default.
1411 return ltr || defaultTheme || "a";
1414 // TODO the following $ and $.fn extensions can/probably should be moved into jquery.mobile.core.helpers
1416 // Find the closest javascript page element to gather settings data jsperf test
1417 // http://jsperf.com/single-complex-selector-vs-many-complex-selectors/edit
1418 // possibly naive, but it shows that the parsing overhead for *just* the page selector vs
1419 // the page and dialog selector is negligable. This could probably be speed up by
1420 // doing a similar parent node traversal to the one found in the inherited theme code above
1421 closestPageData: function( $target ) {
1423 .closest(':jqmData(role="page"), :jqmData(role="dialog")')
1427 enhanceable: function( $set ) {
1428 return this.haveParents( $set, "enhance" );
1431 hijackable: function( $set ) {
1432 return this.haveParents( $set, "ajax" );
1435 haveParents: function( $set, attr ) {
1436 if( !$.mobile.ignoreContentEnabled ){
1440 var count = $set.length,
1442 e, $element, excluded;
1444 for ( var i = 0; i < count; i++ ) {
1445 $element = $set.eq( i );
1450 var c = e.getAttribute ? e.getAttribute( "data-" + $.mobile.ns + attr ) : "";
1452 if ( c === "false" ) {
1461 $newSet = $newSet.add( $element );
1468 getScreenHeight: function(){
1469 // Native innerHeight returns more accurate value for this across platforms,
1470 // jQuery version is here as a normalized fallback for platforms like Symbian
1471 return window.innerHeight || $( window ).height();
1475 // Mobile version of data and removeData and hasData methods
1476 // ensures all data is set and retrieved using jQuery Mobile's data namespace
1477 $.fn.jqmData = function( prop, value ) {
1479 if ( typeof prop != "undefined" ) {
1481 prop = $.mobile.nsNormalize( prop );
1483 result = this.data.apply( this, arguments.length < 2 ? [ prop ] : [ prop, value ] );
1488 $.jqmData = function( elem, prop, value ) {
1490 if ( typeof prop != "undefined" ) {
1491 result = $.data( elem, prop ? $.mobile.nsNormalize( prop ) : prop, value );
1496 $.fn.jqmRemoveData = function( prop ) {
1497 return this.removeData( $.mobile.nsNormalize( prop ) );
1500 $.jqmRemoveData = function( elem, prop ) {
1501 return $.removeData( elem, $.mobile.nsNormalize( prop ) );
1504 $.fn.removeWithDependents = function() {
1505 $.removeWithDependents( this );
1508 $.removeWithDependents = function( elem ) {
1509 var $elem = $( elem );
1511 ( $elem.jqmData('dependents') || $() ).remove();
1515 $.fn.addDependents = function( newDependents ) {
1516 $.addDependents( $(this), newDependents );
1519 $.addDependents = function( elem, newDependents ) {
1520 var dependents = $(elem).jqmData( 'dependents' ) || $();
1522 $(elem).jqmData( 'dependents', $.merge(dependents, newDependents) );
1525 // note that this helper doesn't attempt to handle the callback
1526 // or setting of an html elements text, its only purpose is
1527 // to return the html encoded version of the text in all cases. (thus the name)
1528 $.fn.getEncodedText = function() {
1529 return $( "<div/>" ).text( $(this).text() ).html();
1532 // fluent helper function for the mobile namespaced equivalent
1533 $.fn.jqmEnhanceable = function() {
1534 return $.mobile.enhanceable( this );
1537 $.fn.jqmHijackable = function() {
1538 return $.mobile.hijackable( this );
1541 // Monkey-patching Sizzle to filter the :jqmData selector
1542 var oldFind = $.find,
1543 jqmDataRE = /:jqmData\(([^)]*)\)/g;
1545 $.find = function( selector, context, ret, extra ) {
1546 selector = selector.replace( jqmDataRE, "[data-" + ( $.mobile.ns || "" ) + "$1]" );
1548 return oldFind.call( this, selector, context, ret, extra );
1551 $.extend( $.find, oldFind );
1553 $.find.matches = function( expr, set ) {
1554 return $.find( expr, null, null, set );
1557 $.find.matchesSelector = function( node, expr ) {
1558 return $.find( expr, null, null, [ node ] ).length > 0;
1563 (function( $, undefined ) {
1565 var $window = $( window ),
1566 $html = $( "html" );
1568 /* $.mobile.media method: pass a CSS media type or query and get a bool return
1569 note: this feature relies on actual media query support for media queries, though types will work most anywhere
1571 $.mobile.media('screen') // tests for screen media type
1572 $.mobile.media('screen and (min-width: 480px)') // tests for screen media type with window width > 480px
1573 $.mobile.media('@media screen and (-webkit-min-device-pixel-ratio: 2)') // tests for webkit 2x pixel ratio (iPhone 4)
1575 $.mobile.media = (function() {
1576 // TODO: use window.matchMedia once at least one UA implements it
1578 testDiv = $( "<div id='jquery-mediatest'></div>" ),
1579 fakeBody = $( "<body>" ).append( testDiv );
1581 return function( query ) {
1582 if ( !( query in cache ) ) {
1583 var styleBlock = document.createElement( "style" ),
1584 cssrule = "@media " + query + " { #jquery-mediatest { position:absolute; } }";
1586 //must set type for IE!
1587 styleBlock.type = "text/css";
1589 if ( styleBlock.styleSheet ){
1590 styleBlock.styleSheet.cssText = cssrule;
1592 styleBlock.appendChild( document.createTextNode(cssrule) );
1595 $html.prepend( fakeBody ).prepend( styleBlock );
1596 cache[ query ] = testDiv.css( "position" ) === "absolute";
1597 fakeBody.add( styleBlock ).remove();
1599 return cache[ query ];
1605 (function( $, undefined ) {
1607 var fakeBody = $( "<body>" ).prependTo( "html" ),
1608 fbCSS = fakeBody[ 0 ].style,
1609 vendors = [ "Webkit", "Moz", "O" ],
1610 webos = "palmGetResource" in window, //only used to rule out scrollTop
1611 opera = window.opera,
1612 operamini = window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]",
1613 bb = window.blackberry; //only used to rule out box shadow, as it's filled opaque on BB
1616 function propExists( prop ) {
1617 var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ),
1618 props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " );
1620 for ( var v in props ){
1621 if ( fbCSS[ props[ v ] ] !== undefined ) {
1627 function validStyle( prop, value, check_vend ) {
1628 var div = document.createElement('div'),
1629 uc = function( txt ) {
1630 return txt.charAt( 0 ).toUpperCase() + txt.substr( 1 )
1632 vend_pref = function( vend ) {
1633 return "-" + vend.charAt( 0 ).toLowerCase() + vend.substr( 1 ) + "-";
1635 check_style = function( vend ) {
1636 var vend_prop = vend_pref( vend ) + prop + ": " + value + ";",
1637 uc_vend = uc( vend ),
1638 propStyle = uc_vend + uc( prop );
1640 div.setAttribute( "style", vend_prop );
1642 if( !!div.style[ propStyle ] ) {
1646 check_vends = check_vend ? [ check_vend ] : vendors,
1649 for( i = 0; i < check_vends.length; i++ ) {
1650 check_style( check_vends[i] );
1655 // Thanks to Modernizr src for this test idea. `perspective` check is limited to Moz to prevent a false positive for 3D transforms on Android.
1656 function transform3dTest() {
1657 var prop = "transform-3d";
1658 return validStyle( 'perspective', '10px', 'moz' ) || $.mobile.media( "(-" + vendors.join( "-" + prop + "),(-" ) + "-" + prop + "),(" + prop + ")" );
1661 // Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting )
1662 function baseTagTest() {
1663 var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/",
1664 base = $( "head base" ),
1669 if ( !base.length ) {
1670 base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" );
1672 href = base.attr( "href" );
1675 link = $( "<a href='testurl' />" ).prependTo( fakeBody );
1676 rebase = link[ 0 ].href;
1677 base[ 0 ].href = href || location.pathname;
1682 return rebase.indexOf( fauxBase ) === 0;
1686 function cssPointerEventsTest() {
1687 var element = document.createElement('x'),
1688 documentElement = document.documentElement,
1689 getComputedStyle = window.getComputedStyle,
1692 if( !( 'pointerEvents' in element.style ) ){
1696 element.style.pointerEvents = 'auto';
1697 element.style.pointerEvents = 'x';
1698 documentElement.appendChild(element);
1699 supports = getComputedStyle &&
1700 getComputedStyle( element, '' ).pointerEvents === 'auto';
1701 documentElement.removeChild( element );
1706 // non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683
1707 // allows for inclusion of IE 6+, including Windows Mobile 7
1708 $.extend( $.mobile, { browser: {} } );
1709 $.mobile.browser.ie = (function() {
1711 div = document.createElement( "div" ),
1714 // added {} to silence closure compiler warnings. registering my dislike of all things
1715 // overly clever here for future reference
1716 while ( div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->", a[ 0 ] ){};
1718 return v > 4 ? v : !v;
1722 $.extend( $.support, {
1723 orientation: "orientation" in window && "onorientationchange" in window,
1724 touch: "ontouchend" in document,
1725 cssTransitions: "WebKitTransitionEvent" in window || validStyle( 'transition', 'height 100ms linear' ) && !opera,
1726 pushState: "pushState" in history && "replaceState" in history,
1727 mediaquery: $.mobile.media( "only all" ),
1728 cssPseudoElement: !!propExists( "content" ),
1729 touchOverflow: !!propExists( "overflowScrolling" ),
1730 cssTransform3d: transform3dTest(),
1731 boxShadow: !!propExists( "boxShadow" ) && !bb,
1732 scrollTop: ( "pageXOffset" in window || "scrollTop" in document.documentElement || "scrollTop" in fakeBody[ 0 ] ) && !webos && !operamini,
1733 dynamicBaseTag: baseTagTest(),
1734 cssPointerEvents: cssPointerEventsTest()
1740 // $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian)
1741 // or that generally work better browsing in regular http for full page refreshes (Opera Mini)
1742 // Note: This detection below is used as a last resort.
1743 // We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible
1744 var nokiaLTE7_3 = (function(){
1746 var ua = window.navigator.userAgent;
1748 //The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older
1749 return ua.indexOf( "Nokia" ) > -1 &&
1750 ( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) &&
1751 ua.indexOf( "AppleWebKit" ) > -1 &&
1752 ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ );
1755 // Support conditions that must be met in order to proceed
1756 // default enhanced qualifications are media query support OR IE 7+
1757 $.mobile.gradeA = function(){
1758 return $.support.mediaquery || $.mobile.browser.ie && $.mobile.browser.ie >= 7;
1761 $.mobile.ajaxBlacklist =
1762 // BlackBerry browsers, pre-webkit
1763 window.blackberry && !window.WebKitPoint ||
1766 // Symbian webkits pre 7.3
1769 // Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices
1770 // to render the stylesheets when they're referenced before this script, as we'd recommend doing.
1771 // This simply reappends the CSS in place, which for some reason makes it apply
1772 if ( nokiaLTE7_3 ) {
1774 $( "head link[rel='stylesheet']" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" );
1778 // For ruling out shadows via css
1779 if ( !$.support.boxShadow ) {
1780 $( "html" ).addClass( "ui-mobile-nosupport-boxshadow" );
1785 (function( $, window, undefined ) {
1787 // add new event shortcuts
1788 $.each( ( "touchstart touchmove touchend orientationchange throttledresize " +
1789 "tap taphold swipe swipeleft swiperight scrollstart scrollstop" ).split( " " ), function( i, name ) {
1791 $.fn[ name ] = function( fn ) {
1792 return fn ? this.bind( name, fn ) : this.trigger( name );
1795 $.attrFn[ name ] = true;
1798 var supportTouch = $.support.touch,
1799 scrollEvent = "touchmove scroll",
1800 touchStartEvent = supportTouch ? "touchstart" : "mousedown",
1801 touchStopEvent = supportTouch ? "touchend" : "mouseup",
1802 touchMoveEvent = supportTouch ? "touchmove" : "mousemove";
1804 function triggerCustomEvent( obj, eventType, event ) {
1805 var originalType = event.type;
1806 event.type = eventType;
1807 $.event.handle.call( obj, event );
1808 event.type = originalType;
1811 // also handles scrollstop
1812 $.event.special.scrollstart = {
1818 var thisObject = this,
1819 $this = $( thisObject ),
1823 function trigger( event, state ) {
1825 triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event );
1828 // iPhone triggers scroll after a small delay; use touchmove instead
1829 $this.bind( scrollEvent, function( event ) {
1831 if ( !$.event.special.scrollstart.enabled ) {
1836 trigger( event, true );
1839 clearTimeout( timer );
1840 timer = setTimeout(function() {
1841 trigger( event, false );
1847 // also handles taphold
1848 $.event.special.tap = {
1850 var thisObject = this,
1851 $this = $( thisObject );
1853 $this.bind( "vmousedown", function( event ) {
1855 if ( event.which && event.which !== 1 ) {
1859 var origTarget = event.target,
1860 origEvent = event.originalEvent,
1863 function clearTapTimer() {
1864 clearTimeout( timer );
1867 function clearTapHandlers() {
1870 $this.unbind( "vclick", clickHandler )
1871 .unbind( "vmouseup", clearTapTimer );
1872 $( document ).unbind( "vmousecancel", clearTapHandlers );
1875 function clickHandler(event) {
1878 // ONLY trigger a 'tap' event if the start target is
1879 // the same as the stop target.
1880 if ( origTarget == event.target ) {
1881 triggerCustomEvent( thisObject, "tap", event );
1885 $this.bind( "vmouseup", clearTapTimer )
1886 .bind( "vclick", clickHandler );
1887 $( document ).bind( "vmousecancel", clearTapHandlers );
1889 timer = setTimeout(function() {
1890 triggerCustomEvent( thisObject, "taphold", $.Event( "taphold", { target: origTarget } ) );
1896 // also handles swipeleft, swiperight
1897 $.event.special.swipe = {
1898 scrollSupressionThreshold: 10, // More than this horizontal displacement, and we will suppress scrolling.
1900 durationThreshold: 1000, // More time than this, and it isn't a swipe.
1902 horizontalDistanceThreshold: 30, // Swipe horizontal displacement must be more than this.
1904 verticalDistanceThreshold: 75, // Swipe vertical displacement must be less than this.
1907 var thisObject = this,
1908 $this = $( thisObject );
1910 $this.bind( touchStartEvent, function( event ) {
1911 var data = event.originalEvent.touches ?
1912 event.originalEvent.touches[ 0 ] : event,
1914 time: ( new Date() ).getTime(),
1915 coords: [ data.pageX, data.pageY ],
1916 origin: $( event.target )
1920 function moveHandler( event ) {
1926 var data = event.originalEvent.touches ?
1927 event.originalEvent.touches[ 0 ] : event;
1930 time: ( new Date() ).getTime(),
1931 coords: [ data.pageX, data.pageY ]
1934 // prevent scrolling
1935 if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) {
1936 event.preventDefault();
1940 $this.bind( touchMoveEvent, moveHandler )
1941 .one( touchStopEvent, function( event ) {
1942 $this.unbind( touchMoveEvent, moveHandler );
1944 if ( start && stop ) {
1945 if ( stop.time - start.time < $.event.special.swipe.durationThreshold &&
1946 Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold &&
1947 Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) {
1949 start.origin.trigger( "swipe" )
1950 .trigger( start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight" );
1953 start = stop = undefined;
1959 (function( $, window ) {
1960 // "Cowboy" Ben Alman
1962 var win = $( window ),
1966 initial_orientation_is_landscape,
1967 initial_orientation_is_default,
1968 portrait_map = { "0": true, "180": true };
1970 // It seems that some device/browser vendors use window.orientation values 0 and 180 to
1971 // denote the "default" orientation. For iOS devices, and most other smart-phones tested,
1972 // the default orientation is always "portrait", but in some Android and RIM based tablets,
1973 // the default orientation is "landscape". The following code attempts to use the window
1974 // dimensions to figure out what the current orientation is, and then makes adjustments
1975 // to the to the portrait_map if necessary, so that we can properly decode the
1976 // window.orientation value whenever get_orientation() is called.
1978 // Note that we used to use a media query to figure out what the orientation the browser
1981 // initial_orientation_is_landscape = $.mobile.media("all and (orientation: landscape)");
1983 // but there was an iPhone/iPod Touch bug beginning with iOS 4.2, up through iOS 5.1,
1984 // where the browser *ALWAYS* applied the landscape media query. This bug does not
1987 if ( $.support.orientation ) {
1989 // Check the window width and height to figure out what the current orientation
1990 // of the device is at this moment. Note that we've initialized the portrait map
1991 // values to 0 and 180, *AND* we purposely check for landscape so that if we guess
1992 // wrong, , we default to the assumption that portrait is the default orientation.
1993 // We use a threshold check below because on some platforms like iOS, the iPhone
1994 // form-factor can report a larger width than height if the user turns on the
1995 // developer console. The actual threshold value is somewhat arbitrary, we just
1996 // need to make sure it is large enough to exclude the developer console case.
1998 var ww = window.innerWidth || $( window ).width(),
1999 wh = window.innerHeight || $( window ).height(),
2000 landscape_threshold = 50;
2002 initial_orientation_is_landscape = ww > wh && ( ww - wh ) > landscape_threshold;
2005 // Now check to see if the current window.orientation is 0 or 180.
2006 initial_orientation_is_default = portrait_map[ window.orientation ];
2008 // If the initial orientation is landscape, but window.orientation reports 0 or 180, *OR*
2009 // if the initial orientation is portrait, but window.orientation reports 90 or -90, we
2010 // need to flip our portrait_map values because landscape is the default orientation for
2011 // this device/browser.
2012 if ( ( initial_orientation_is_landscape && initial_orientation_is_default ) || ( !initial_orientation_is_landscape && !initial_orientation_is_default ) ) {
2013 portrait_map = { "-90": true, "90": true };
2017 $.event.special.orientationchange = special_event = {
2019 // If the event is supported natively, return false so that jQuery
2020 // will bind to the event using DOM methods.
2021 if ( $.support.orientation && $.mobile.orientationChangeEnabled ) {
2025 // Get the current orientation to avoid initial double-triggering.
2026 last_orientation = get_orientation();
2028 // Because the orientationchange event doesn't exist, simulate the
2029 // event by testing window dimensions on resize.
2030 win.bind( "throttledresize", handler );
2032 teardown: function(){
2033 // If the event is supported natively, return false so that
2034 // jQuery will unbind the event using DOM methods.
2035 if ( $.support.orientation && $.mobile.orientationChangeEnabled ) {
2039 // Because the orientationchange event doesn't exist, unbind the
2040 // resize event handler.
2041 win.unbind( "throttledresize", handler );
2043 add: function( handleObj ) {
2044 // Save a reference to the bound event handler.
2045 var old_handler = handleObj.handler;
2048 handleObj.handler = function( event ) {
2049 // Modify event object, adding the .orientation property.
2050 event.orientation = get_orientation();
2052 // Call the originally-bound event handler and return its result.
2053 return old_handler.apply( this, arguments );
2058 // If the event is not supported natively, this handler will be bound to
2059 // the window resize event to simulate the orientationchange event.
2060 function handler() {
2061 // Get the current orientation.
2062 var orientation = get_orientation();
2064 if ( orientation !== last_orientation ) {
2065 // The orientation has changed, so trigger the orientationchange event.
2066 last_orientation = orientation;
2067 win.trigger( "orientationchange" );
2071 // Get the current page orientation. This method is exposed publicly, should it
2072 // be needed, as jQuery.event.special.orientationchange.orientation()
2073 $.event.special.orientationchange.orientation = get_orientation = function() {
2074 var isPortrait = true, elem = document.documentElement;
2076 // prefer window orientation to the calculation based on screensize as
2077 // the actual screen resize takes place before or after the orientation change event
2078 // has been fired depending on implementation (eg android 2.3 is before, iphone after).
2079 // More testing is required to determine if a more reliable method of determining the new screensize
2080 // is possible when orientationchange is fired. (eg, use media queries + element + opacity)
2081 if ( $.support.orientation ) {
2082 // if the window orientation registers as 0 or 180 degrees report
2083 // portrait, otherwise landscape
2084 isPortrait = portrait_map[ window.orientation ];
2086 isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1;
2089 return isPortrait ? "portrait" : "landscape";
2092 })( jQuery, window );
2095 // throttled resize event
2098 $.event.special.throttledresize = {
2100 $( this ).bind( "resize", handler );
2102 teardown: function(){
2103 $( this ).unbind( "resize", handler );
2108 handler = function() {
2109 curr = ( new Date() ).getTime();
2110 diff = curr - lastCall;
2112 if ( diff >= throttle ) {
2115 $( this ).trigger( "throttledresize" );
2120 clearTimeout( heldCall );
2123 // Promise a held call will still execute
2124 heldCall = setTimeout( handler, throttle - diff );
2135 scrollstop: "scrollstart",
2139 }, function( event, sourceEvent ) {
2141 $.event.special[ event ] = {
2143 $( this ).bind( sourceEvent, $.noop );
2150 (function( $, undefined ) {
2152 $.widget( "mobile.page", $.mobile.widget, {
2156 keepNativeDefault: ":jqmData(role='none'), :jqmData(role='nojs')"
2159 _create: function() {
2163 // if false is returned by the callbacks do not create the page
2164 if( self._trigger( "beforecreate" ) === false ){
2169 .attr( "tabindex", "0" )
2170 .addClass( "ui-page ui-body-" + self.options.theme )
2171 .bind( "pagebeforehide", function(){
2172 self.removeContainerBackground();
2174 .bind( "pagebeforeshow", function(){
2175 self.setContainerBackground();
2180 removeContainerBackground: function(){
2181 $.mobile.pageContainer.removeClass( "ui-overlay-" + $.mobile.getInheritedTheme( this.element.parent() ) );
2184 // set the page container background to the page theme
2185 setContainerBackground: function( theme ){
2186 if( this.options.theme ){
2187 $.mobile.pageContainer.addClass( "ui-overlay-" + ( theme || this.options.theme ) );
2191 keepNativeSelector: function() {
2192 var options = this.options,
2193 keepNativeDefined = options.keepNative && $.trim(options.keepNative);
2195 if( keepNativeDefined && options.keepNative !== options.keepNativeDefault ){
2196 return [options.keepNative, options.keepNativeDefault].join(", ");
2199 return options.keepNativeDefault;
2205 (function( $, window, undefined ) {
2207 var createHandler = function( sequential ){
2209 // Default to sequential
2210 if( sequential === undefined ){
2214 return function( name, reverse, $to, $from ) {
2216 var deferred = new $.Deferred(),
2217 reverseClass = reverse ? " reverse" : "",
2218 active = $.mobile.urlHistory.getActive(),
2219 toScroll = active.lastScroll || $.mobile.defaultHomeScroll,
2220 screenHeight = $.mobile.getScreenHeight(),
2221 maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $( window ).width() > $.mobile.maxTransitionWidth,
2222 none = !$.support.cssTransitions || maxTransitionOverride || !name || name === "none" || Math.max( $( window ).scrollTop(), toScroll ) > $.mobile.getMaxScrollForTransition(),
2223 toPreClass = " ui-page-pre-in",
2224 toggleViewportClass = function(){
2225 $.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + name );
2227 scrollPage = function(){
2228 // By using scrollTo instead of silentScroll, we can keep things better in order
2229 // Just to be precautios, disable scrollstart listening like silentScroll would
2230 $.event.special.scrollstart.enabled = false;
2232 window.scrollTo( 0, toScroll );
2234 // reenable scrollstart listening like silentScroll would
2235 setTimeout(function() {
2236 $.event.special.scrollstart.enabled = true;
2239 cleanFrom = function(){
2241 .removeClass( $.mobile.activePageClass + " out in reverse " + name )
2244 startOut = function(){
2245 // if it's not sequential, call the doneOut transition to start the TO page animating in simultaneously
2250 $from.animationComplete( doneOut );
2253 // Set the from page's height and start it transitioning out
2254 // Note: setting an explicit height helps eliminate tiling in the transitions
2256 .height( screenHeight + $(window ).scrollTop() )
2257 .addClass( name + " out" + reverseClass );
2260 doneOut = function() {
2262 if ( $from && sequential ) {
2269 startIn = function(){
2271 $to.addClass( $.mobile.activePageClass );
2273 // Send focus to page as it is now display: block
2274 $.mobile.focusPage( $to );
2276 // Set to page height
2277 $to.height( screenHeight + toScroll );
2282 $to.animationComplete( doneIn );
2285 $to.addClass( name + " in" + reverseClass );
2293 doneIn = function() {
2295 if ( !sequential ) {
2303 .removeClass( "out in reverse " + name )
2306 toggleViewportClass();
2308 // In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition
2309 // This ensures we jump to that spot after the fact, if we aren't there already.
2310 if( $( window ).scrollTop() !== toScroll ){
2314 deferred.resolve( name, reverse, $to, $from, true );
2317 toggleViewportClass();
2319 if ( $from && !none ) {
2326 return deferred.promise();
2330 // generate the handlers from the above
2331 var sequentialHandler = createHandler(),
2332 simultaneousHandler = createHandler( false ),
2333 defaultGetMaxScrollForTransition = function() {
2334 return $.mobile.getScreenHeight() * 3;
2337 // Make our transition handler the public default.
2338 $.mobile.defaultTransitionHandler = sequentialHandler;
2340 //transition handler dictionary for 3rd party transitions
2341 $.mobile.transitionHandlers = {
2342 "default": $.mobile.defaultTransitionHandler,
2343 "sequential": sequentialHandler,
2344 "simultaneous": simultaneousHandler
2347 $.mobile.transitionFallbacks = {};
2349 // Set the getMaxScrollForTransition to default if no implementation was set by user
2350 $.mobile.getMaxScrollForTransition = $.mobile.getMaxScrollForTransition || defaultGetMaxScrollForTransition;
2353 ( function( $, undefined ) {
2355 //define vars for interal use
2356 var $window = $( window ),
2357 $html = $( 'html' ),
2358 $head = $( 'head' ),
2360 //url path helpers for use in relative url management
2363 // This scary looking regular expression parses an absolute URL or its relative
2364 // variants (protocol, site, document, query, and hash), into the various
2365 // components (protocol, host, path, query, fragment, etc that make up the
2366 // URL as well as some other commonly used sub-parts. When used with RegExp.exec()
2367 // or String.match, it parses the URL into a results array that looks like this:
2369 // [0]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread#msg-content
2370 // [1]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread
2371 // [2]: http://jblas:password@mycompany.com:8080/mail/inbox
2372 // [3]: http://jblas:password@mycompany.com:8080
2375 // [6]: jblas:password@mycompany.com:8080
2376 // [7]: jblas:password
2379 // [10]: mycompany.com:8080
2380 // [11]: mycompany.com
2382 // [13]: /mail/inbox
2385 // [16]: ?msg=1234&type=unread
2386 // [17]: #msg-content
2388 urlParseRE: /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,
2390 //Parse a URL into a structure that allows easy access to
2391 //all of the URL components by name.
2392 parseUrl: function( url ) {
2393 // If we're passed an object, we'll assume that it is
2394 // a parsed url object and just return it back to the caller.
2395 if ( $.type( url ) === "object" ) {
2399 var matches = path.urlParseRE.exec( url || "" ) || [];
2401 // Create an object that allows the caller to access the sub-matches
2402 // by name. Note that IE returns an empty string instead of undefined,
2403 // like all other browsers do, so we normalize everything so its consistent
2404 // no matter what browser we're running on.
2406 href: matches[ 0 ] || "",
2407 hrefNoHash: matches[ 1 ] || "",
2408 hrefNoSearch: matches[ 2 ] || "",
2409 domain: matches[ 3 ] || "",
2410 protocol: matches[ 4 ] || "",
2411 doubleSlash: matches[ 5 ] || "",
2412 authority: matches[ 6 ] || "",
2413 username: matches[ 8 ] || "",
2414 password: matches[ 9 ] || "",
2415 host: matches[ 10 ] || "",
2416 hostname: matches[ 11 ] || "",
2417 port: matches[ 12 ] || "",
2418 pathname: matches[ 13 ] || "",
2419 directory: matches[ 14 ] || "",
2420 filename: matches[ 15 ] || "",
2421 search: matches[ 16 ] || "",
2422 hash: matches[ 17 ] || ""
2426 //Turn relPath into an asbolute path. absPath is
2427 //an optional absolute path which describes what
2428 //relPath is relative to.
2429 makePathAbsolute: function( relPath, absPath ) {
2430 if ( relPath && relPath.charAt( 0 ) === "/" ) {
2434 relPath = relPath || "";
2435 absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : "";
2437 var absStack = absPath ? absPath.split( "/" ) : [],
2438 relStack = relPath.split( "/" );
2439 for ( var i = 0; i < relStack.length; i++ ) {
2440 var d = relStack[ i ];
2445 if ( absStack.length ) {
2454 return "/" + absStack.join( "/" );
2457 //Returns true if both urls have the same domain.
2458 isSameDomain: function( absUrl1, absUrl2 ) {
2459 return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain;
2462 //Returns true for any relative variant.
2463 isRelativeUrl: function( url ) {
2464 // All relative Url variants have one thing in common, no protocol.
2465 return path.parseUrl( url ).protocol === "";
2468 //Returns true for an absolute url.
2469 isAbsoluteUrl: function( url ) {
2470 return path.parseUrl( url ).protocol !== "";
2473 //Turn the specified realtive URL into an absolute one. This function
2474 //can handle all relative variants (protocol, site, document, query, fragment).
2475 makeUrlAbsolute: function( relUrl, absUrl ) {
2476 if ( !path.isRelativeUrl( relUrl ) ) {
2480 var relObj = path.parseUrl( relUrl ),
2481 absObj = path.parseUrl( absUrl ),
2482 protocol = relObj.protocol || absObj.protocol,
2483 doubleSlash = relObj.protocol ? relObj.doubleSlash : ( relObj.doubleSlash || absObj.doubleSlash ),
2484 authority = relObj.authority || absObj.authority,
2485 hasPath = relObj.pathname !== "",
2486 pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ),
2487 search = relObj.search || ( !hasPath && absObj.search ) || "",
2490 return protocol + doubleSlash + authority + pathname + search + hash;
2493 //Add search (aka query) params to the specified url.
2494 addSearchParams: function( url, params ) {
2495 var u = path.parseUrl( url ),
2496 p = ( typeof params === "object" ) ? $.param( params ) : params,
2497 s = u.search || "?";
2498 return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" );
2501 convertUrlToDataUrl: function( absUrl ) {
2502 var u = path.parseUrl( absUrl );
2503 if ( path.isEmbeddedPage( u ) ) {
2504 // For embedded pages, remove the dialog hash key as in getFilePath(),
2505 // otherwise the Data Url won't match the id of the embedded Page.
2506 return u.hash.split( dialogHashKey )[0].replace( /^#/, "" );
2507 } else if ( path.isSameDomain( u, documentBase ) ) {
2508 return u.hrefNoHash.replace( documentBase.domain, "" ).split( dialogHashKey )[0];
2513 //get path from current hash, or from a file path
2514 get: function( newPath ) {
2515 if( newPath === undefined ) {
2516 newPath = location.hash;
2518 return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, '' );
2521 //return the substring of a filepath before the sub-page key, for making a server request
2522 getFilePath: function( path ) {
2523 var splitkey = '&' + $.mobile.subPageUrlKey;
2524 return path && path.split( splitkey )[0].split( dialogHashKey )[0];
2527 //set location hash to path
2528 set: function( path ) {
2529 location.hash = path;
2532 //test if a given url (string) is a path
2533 //NOTE might be exceptionally naive
2534 isPath: function( url ) {
2535 return ( /\// ).test( url );
2538 //return a url path with the window's location protocol/hostname/pathname removed
2539 clean: function( url ) {
2540 return url.replace( documentBase.domain, "" );
2543 //just return the url without an initial #
2544 stripHash: function( url ) {
2545 return url.replace( /^#/, "" );
2548 //remove the preceding hash, any query params, and dialog notations
2549 cleanHash: function( hash ) {
2550 return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) );
2553 isHashValid: function( hash ) {
2554 return /^#[^#]+$/.test(hash);
2557 //check whether a url is referencing the same domain, or an external domain or different protocol
2558 //could be mailto, etc
2559 isExternal: function( url ) {
2560 var u = path.parseUrl( url );
2561 return u.protocol && u.domain !== documentUrl.domain ? true : false;
2564 hasProtocol: function( url ) {
2565 return ( /^(:?\w+:)/ ).test( url );
2568 //check if the specified url refers to the first page in the main application document.
2569 isFirstPageUrl: function( url ) {
2570 // We only deal with absolute paths.
2571 var u = path.parseUrl( path.makeUrlAbsolute( url, documentBase ) ),
2573 // Does the url have the same path as the document?
2574 samePath = u.hrefNoHash === documentUrl.hrefNoHash || ( documentBaseDiffers && u.hrefNoHash === documentBase.hrefNoHash ),
2576 // Get the first page element.
2577 fp = $.mobile.firstPage,
2579 // Get the id of the first page element if it has one.
2580 fpId = fp && fp[0] ? fp[0].id : undefined;
2582 // The url refers to the first page if the path matches the document and
2583 // it either has no hash value, or the hash is exactly equal to the id of the
2584 // first page element.
2585 return samePath && ( !u.hash || u.hash === "#" || ( fpId && u.hash.replace( /^#/, "" ) === fpId ) );
2588 isEmbeddedPage: function( url ) {
2589 var u = path.parseUrl( url );
2591 //if the path is absolute, then we need to compare the url against
2592 //both the documentUrl and the documentBase. The main reason for this
2593 //is that links embedded within external documents will refer to the
2594 //application document, whereas links embedded within the application
2595 //document will be resolved against the document base.
2596 if ( u.protocol !== "" ) {
2597 return ( u.hash && ( u.hrefNoHash === documentUrl.hrefNoHash || ( documentBaseDiffers && u.hrefNoHash === documentBase.hrefNoHash ) ) );
2599 return (/^#/).test( u.href );
2603 // Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
2604 // requests if the document doing the request was loaded via the file:// protocol.
2605 // This is usually to allow the application to "phone home" and fetch app specific
2606 // data. We normally let the browser handle external/cross-domain urls, but if the
2607 // allowCrossDomainPages option is true, we will allow cross-domain http/https
2608 // requests to go through our page loading logic.
2609 isPermittedCrossDomainRequest: function( docUrl, reqUrl ) {
2610 return $.mobile.allowCrossDomainPages
2611 && docUrl.protocol === "file:"
2612 && reqUrl.search( /^https?:/ ) != -1;
2616 //will be defined when a link is clicked and given an active class
2617 $activeClickedLink = null,
2619 //urlHistory is purely here to make guesses at whether the back or forward button was clicked
2620 //and provide an appropriate transition
2622 // Array of pages that are visited during a single page load.
2623 // Each has a url and optional transition, title, and pageUrl (which represents the file path, in cases where URL is obscured, such as dialogs)
2626 //maintain an index number for the active page in the stack
2630 getActive: function() {
2631 return urlHistory.stack[ urlHistory.activeIndex ];
2634 getPrev: function() {
2635 return urlHistory.stack[ urlHistory.activeIndex - 1 ];
2638 getNext: function() {
2639 return urlHistory.stack[ urlHistory.activeIndex + 1 ];
2642 // addNew is used whenever a new page is added
2643 addNew: function( url, transition, title, pageUrl, role ) {
2644 //if there's forward history, wipe it
2645 if( urlHistory.getNext() ) {
2646 urlHistory.clearForward();
2649 urlHistory.stack.push( {url : url, transition: transition, title: title, pageUrl: pageUrl, role: role } );
2651 urlHistory.activeIndex = urlHistory.stack.length - 1;
2654 //wipe urls ahead of active index
2655 clearForward: function() {
2656 urlHistory.stack = urlHistory.stack.slice( 0, urlHistory.activeIndex + 1 );
2659 directHashChange: function( opts ) {
2660 var back , forward, newActiveIndex, prev = this.getActive();
2662 // check if url is in history and if it's ahead or behind current page
2663 $.each( urlHistory.stack, function( i, historyEntry ) {
2665 //if the url is in the stack, it's a forward or a back
2666 if( opts.currentUrl === historyEntry.url ) {
2667 //define back and forward by whether url is older or newer than current page
2668 back = i < urlHistory.activeIndex;
2674 // save new page index, null check to prevent falsey 0 result
2675 this.activeIndex = newActiveIndex !== undefined ? newActiveIndex : this.activeIndex;
2678 ( opts.either || opts.isBack )( true );
2679 } else if( forward ) {
2680 ( opts.either || opts.isForward )( false );
2684 //disable hashchange event listener internally to ignore one change
2685 //toggled internally when location.hash is updated to match the url of a successful page load
2686 ignoreNextHashChange: false
2689 //define first selector to receive focus when a page is shown
2690 focusable = "[tabindex],a,button:visible,select:visible,input",
2692 //queue to hold simultanious page transitions
2693 pageTransitionQueue = [],
2695 //indicates whether or not page is in process of transitioning
2696 isPageTransitioning = false,
2698 //nonsense hash change key for dialogs, so they create a history entry
2699 dialogHashKey = "&ui-state=dialog",
2701 //existing base tag?
2702 $base = $head.children( "base" ),
2704 //tuck away the original document URL minus any fragment.
2705 documentUrl = path.parseUrl( location.href ),
2707 //if the document has an embedded base tag, documentBase is set to its
2708 //initial value. If a base tag does not exist, then we default to the documentUrl.
2709 documentBase = $base.length ? path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), documentUrl.href ) ) : documentUrl,
2711 //cache the comparison once.
2712 documentBaseDiffers = ( documentUrl.hrefNoHash !== documentBase.hrefNoHash ),
2714 getScreenHeight = $.mobile.getScreenHeight;
2716 //base element management, defined depending on dynamic base tag support
2717 var base = $.support.dynamicBaseTag ? {
2719 //define base element, for use in routing asset urls that are referenced in Ajax-requested markup
2720 element: ( $base.length ? $base : $( "<base>", { href: documentBase.hrefNoHash } ).prependTo( $head ) ),
2722 //set the generated BASE element's href attribute to a new page's base path
2723 set: function( href ) {
2724 base.element.attr( "href", path.makeUrlAbsolute( href, documentBase ) );
2727 //set the generated BASE element's href attribute to a new page's base path
2729 base.element.attr( "href", documentBase.hrefNoHash );
2735 internal utility functions
2736 --------------------------------------*/
2739 //direct focus to the page title, or otherwise first focusable element
2740 $.mobile.focusPage = function ( page ) {
2741 var autofocus = page.find("[autofocus]"),
2742 pageTitle = page.find( ".ui-title:eq(0)" );
2744 if( autofocus.length ) {
2749 if( pageTitle.length ) {
2757 //remove active classes after page transition or error
2758 function removeActiveLinkClass( forceRemoval ) {
2759 if( !!$activeClickedLink && ( !$activeClickedLink.closest( '.ui-page-active' ).length || forceRemoval ) ) {
2760 $activeClickedLink.removeClass( $.mobile.activeBtnClass );
2762 $activeClickedLink = null;
2765 function releasePageTransitionLock() {
2766 isPageTransitioning = false;
2767 if( pageTransitionQueue.length > 0 ) {
2768 $.mobile.changePage.apply( null, pageTransitionQueue.pop() );
2772 // Save the last scroll distance per page, before it is hidden
2773 var setLastScrollEnabled = true,
2774 setLastScroll, delayedSetLastScroll;
2776 setLastScroll = function() {
2777 // this barrier prevents setting the scroll value based on the browser
2778 // scrolling the window based on a hashchange
2779 if( !setLastScrollEnabled ) {
2783 var active = $.mobile.urlHistory.getActive();
2786 var lastScroll = $window.scrollTop();
2788 // Set active page's lastScroll prop.
2789 // If the location we're scrolling to is less than minScrollBack, let it go.
2790 active.lastScroll = lastScroll < $.mobile.minScrollBack ? $.mobile.defaultHomeScroll : lastScroll;
2794 // bind to scrollstop to gather scroll position. The delay allows for the hashchange
2795 // event to fire and disable scroll recording in the case where the browser scrolls
2796 // to the hash targets location (sometimes the top of the page). once pagechange fires
2797 // getLastScroll is again permitted to operate
2798 delayedSetLastScroll = function() {
2799 setTimeout( setLastScroll, 100 );
2802 // disable an scroll setting when a hashchange has been fired, this only works
2803 // because the recording of the scroll position is delayed for 100ms after
2804 // the browser might have changed the position because of the hashchange
2805 $window.bind( $.support.pushState ? "popstate" : "hashchange", function() {
2806 setLastScrollEnabled = false;
2809 // handle initial hashchange from chrome :(
2810 $window.one( $.support.pushState ? "popstate" : "hashchange", function() {
2811 setLastScrollEnabled = true;
2814 // wait until the mobile page container has been determined to bind to pagechange
2815 $window.one( "pagecontainercreate", function(){
2816 // once the page has changed, re-enable the scroll recording
2817 $.mobile.pageContainer.bind( "pagechange", function() {
2819 setLastScrollEnabled = true;
2821 // remove any binding that previously existed on the get scroll
2822 // which may or may not be different than the scroll element determined for
2823 // this page previously
2824 $window.unbind( "scrollstop", delayedSetLastScroll );
2826 // determine and bind to the current scoll element which may be the window
2827 // or in the case of touch overflow the element with touch overflow
2828 $window.bind( "scrollstop", delayedSetLastScroll );
2832 // bind to scrollstop for the first page as "pagechange" won't be fired in that case
2833 $window.bind( "scrollstop", delayedSetLastScroll );
2835 //function for transitioning between two existing pages
2836 function transitionPages( toPage, fromPage, transition, reverse ) {
2839 //trigger before show/hide events
2840 fromPage.data( "page" )._trigger( "beforehide", null, { nextPage: toPage } );
2843 toPage.data( "page" )._trigger( "beforeshow", null, { prevPage: fromPage || $( "" ) } );
2846 $.mobile.hidePageLoadingMsg();
2848 // If transition is defined, check if css 3D transforms are supported, and if not, if a fallback is specified
2849 if( transition && !$.support.cssTransform3d && $.mobile.transitionFallbacks[ transition ] ){
2850 transition = $.mobile.transitionFallbacks[ transition ];
2853 //find the transition handler for the specified transition. If there
2854 //isn't one in our transitionHandlers dictionary, use the default one.
2855 //call the handler immediately to kick-off the transition.
2856 var th = $.mobile.transitionHandlers[ transition || "default" ] || $.mobile.defaultTransitionHandler,
2857 promise = th( transition, reverse, toPage, fromPage );
2859 promise.done(function() {
2861 //trigger show/hide events
2863 fromPage.data( "page" )._trigger( "hide", null, { nextPage: toPage } );
2866 //trigger pageshow, define prevPage as either fromPage or empty jQuery obj
2867 toPage.data( "page" )._trigger( "show", null, { prevPage: fromPage || $( "" ) } );
2873 //simply set the active page's minimum height to screen height, depending on orientation
2874 function resetActivePageHeight(){
2875 var aPage = $( "." + $.mobile.activePageClass ),
2876 aPagePadT = parseFloat( aPage.css( "padding-top" ) ),
2877 aPagePadB = parseFloat( aPage.css( "padding-bottom" ) ),
2878 aPageBorderT = parseFloat( aPage.css( "border-top-width" ) ),
2879 aPageBorderB = parseFloat( aPage.css( "border-bottom-width" ) );
2881 aPage.css( "min-height", getScreenHeight() - aPagePadT - aPagePadB - aPageBorderT - aPageBorderB );
2884 //shared page enhancements
2885 function enhancePage( $page, role ) {
2886 // If a role was specified, make sure the data-role attribute
2887 // on the page element is in sync.
2889 $page.attr( "data-" + $.mobile.ns + "role", role );
2896 /* exposed $.mobile methods */
2898 //animation complete callback
2899 $.fn.animationComplete = function( callback ) {
2900 if( $.support.cssTransitions ) {
2901 return $( this ).one( 'webkitAnimationEnd animationend', callback );
2904 // defer execution for consistency between webkit/non webkit
2905 setTimeout( callback, 0 );
2910 //expose path object on $.mobile
2911 $.mobile.path = path;
2913 //expose base object on $.mobile
2914 $.mobile.base = base;
2917 $.mobile.urlHistory = urlHistory;
2919 $.mobile.dialogHashKey = dialogHashKey;
2923 //enable cross-domain page support
2924 $.mobile.allowCrossDomainPages = false;
2926 //return the original document url
2927 $.mobile.getDocumentUrl = function(asParsedObject) {
2928 return asParsedObject ? $.extend( {}, documentUrl ) : documentUrl.href;
2931 //return the original document base url
2932 $.mobile.getDocumentBase = function(asParsedObject) {
2933 return asParsedObject ? $.extend( {}, documentBase ) : documentBase.href;
2936 $.mobile._bindPageRemove = function() {
2939 // when dom caching is not enabled or the page is embedded bind to remove the page on hide
2940 if( !page.data("page").options.domCache
2941 && page.is(":jqmData(external-page='true')") ) {
2943 page.bind( 'pagehide.remove', function() {
2944 var $this = $( this ),
2945 prEvent = new $.Event( "pageremove" );
2947 $this.trigger( prEvent );
2949 if( !prEvent.isDefaultPrevented() ){
2950 $this.removeWithDependents();
2956 // Load a page into the DOM.
2957 $.mobile.loadPage = function( url, options ) {
2958 // This function uses deferred notifications to let callers
2959 // know when the page is done loading, or if an error has occurred.
2960 var deferred = $.Deferred(),
2962 // The default loadPage options with overrides specified by
2964 settings = $.extend( {}, $.mobile.loadPage.defaults, options ),
2966 // The DOM element for the page after it has been loaded.
2969 // If the reloadPage option is true, and the page is already
2970 // in the DOM, dupCachedPage will be set to the page element
2971 // so that it can be removed after the new version of the
2972 // page is loaded off the network.
2973 dupCachedPage = null,
2975 // determine the current base url
2976 findBaseWithDefault = function(){
2977 var closestBase = ( $.mobile.activePage && getClosestBaseUrl( $.mobile.activePage ) );
2978 return closestBase || documentBase.hrefNoHash;
2981 // The absolute version of the URL passed into the function. This
2982 // version of the URL may contain dialog/subpage params in it.
2983 absUrl = path.makeUrlAbsolute( url, findBaseWithDefault() );
2986 // If the caller provided data, and we're using "get" request,
2987 // append the data to the URL.
2988 if ( settings.data && settings.type === "get" ) {
2989 absUrl = path.addSearchParams( absUrl, settings.data );
2990 settings.data = undefined;
2993 // If the caller is using a "post" request, reloadPage must be true
2994 if( settings.data && settings.type === "post" ){
2995 settings.reloadPage = true;
2998 // The absolute version of the URL minus any dialog/subpage params.
2999 // In otherwords the real URL of the page to be loaded.
3000 var fileUrl = path.getFilePath( absUrl ),
3002 // The version of the Url actually stored in the data-url attribute of
3003 // the page. For embedded pages, it is just the id of the page. For pages
3004 // within the same domain as the document base, it is the site relative
3005 // path. For cross-domain pages (Phone Gap only) the entire absolute Url
3006 // used to load the page.
3007 dataUrl = path.convertUrlToDataUrl( absUrl );
3009 // Make sure we have a pageContainer to work with.
3010 settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
3012 // Check to see if the page already exists in the DOM.
3013 page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" );
3015 // If we failed to find the page, check to see if the url is a
3016 // reference to an embedded page. If so, it may have been dynamically
3017 // injected by a developer, in which case it would be lacking a data-url
3018 // attribute and in need of enhancement.
3019 if ( page.length === 0 && dataUrl && !path.isPath( dataUrl ) ) {
3020 page = settings.pageContainer.children( "#" + dataUrl )
3021 .attr( "data-" + $.mobile.ns + "url", dataUrl );
3024 // If we failed to find a page in the DOM, check the URL to see if it
3025 // refers to the first page in the application. If it isn't a reference
3026 // to the first page and refers to non-existent embedded page, error out.
3027 if ( page.length === 0 ) {
3028 if ( $.mobile.firstPage && path.isFirstPageUrl( fileUrl ) ) {
3029 // Check to make sure our cached-first-page is actually
3030 // in the DOM. Some user deployed apps are pruning the first
3031 // page from the DOM for various reasons, we check for this
3032 // case here because we don't want a first-page with an id
3033 // falling through to the non-existent embedded page error
3034 // case. If the first-page is not in the DOM, then we let
3035 // things fall through to the ajax loading code below so
3036 // that it gets reloaded.
3037 if ( $.mobile.firstPage.parent().length ) {
3038 page = $( $.mobile.firstPage );
3040 } else if ( path.isEmbeddedPage( fileUrl ) ) {
3041 deferred.reject( absUrl, options );
3042 return deferred.promise();
3046 // Reset base to the default document base.
3051 // If the page we are interested in is already in the DOM,
3052 // and the caller did not indicate that we should force a
3053 // reload of the file, we are done. Otherwise, track the
3054 // existing page as a duplicated.
3055 if ( page.length ) {
3056 if ( !settings.reloadPage ) {
3057 enhancePage( page, settings.role );
3058 deferred.resolve( absUrl, options, page );
3059 return deferred.promise();
3061 dupCachedPage = page;
3064 var mpc = settings.pageContainer,
3065 pblEvent = new $.Event( "pagebeforeload" ),
3066 triggerData = { url: url, absUrl: absUrl, dataUrl: dataUrl, deferred: deferred, options: settings };
3068 // Let listeners know we're about to load a page.
3069 mpc.trigger( pblEvent, triggerData );
3071 // If the default behavior is prevented, stop here!
3072 if( pblEvent.isDefaultPrevented() ){
3073 return deferred.promise();
3076 if ( settings.showLoadMsg ) {
3078 // This configurable timeout allows cached pages a brief delay to load without showing a message
3079 var loadMsgDelay = setTimeout(function(){
3080 $.mobile.showPageLoadingMsg();
3081 }, settings.loadMsgDelay ),
3083 // Shared logic for clearing timeout and removing message.
3084 hideMsg = function(){
3086 // Stop message show timer
3087 clearTimeout( loadMsgDelay );
3089 // Hide loading message
3090 $.mobile.hidePageLoadingMsg();
3094 if ( !( $.mobile.allowCrossDomainPages || path.isSameDomain( documentUrl, absUrl ) ) ) {
3095 deferred.reject( absUrl, options );
3097 // Load the new page.
3100 type: settings.type,
3101 data: settings.data,
3103 success: function( html, textStatus, xhr ) {
3104 //pre-parse html to check for a data-url,
3105 //use it as the new fileUrl, base path, etc
3106 var all = $( "<div></div>" ),
3109 newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1,
3111 // TODO handle dialogs again
3112 pageElemRegex = new RegExp( "(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?page[\"']?[^>]*>)" ),
3113 dataUrlRegex = new RegExp( "\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?" );
3116 // data-url must be provided for the base tag so resource requests can be directed to the
3117 // correct url. loading into a temprorary element makes these requests immediately
3118 if( pageElemRegex.test( html )
3120 && dataUrlRegex.test( RegExp.$1 )
3122 url = fileUrl = path.getFilePath( RegExp.$1 );
3126 base.set( fileUrl );
3129 //workaround to allow scripts to execute when included in page divs
3130 all.get( 0 ).innerHTML = html;
3131 page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first();
3133 //if page elem couldn't be found, create one and insert the body element's contents
3135 page = $( "<div data-" + $.mobile.ns + "role='page'>" + html.split( /<\/?body[^>]*>/gmi )[1] + "</div>" );
3138 if ( newPageTitle && !page.jqmData( "title" ) ) {
3139 if ( ~newPageTitle.indexOf( "&" ) ) {
3140 newPageTitle = $( "<div>" + newPageTitle + "</div>" ).text();
3142 page.jqmData( "title", newPageTitle );
3145 //rewrite src and href attrs to use a base url
3146 if( !$.support.dynamicBaseTag ) {
3147 var newPath = path.get( fileUrl );
3148 page.find( "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]" ).each(function() {
3149 var thisAttr = $( this ).is( '[href]' ) ? 'href' :
3150 $(this).is('[src]') ? 'src' : 'action',
3151 thisUrl = $( this ).attr( thisAttr );
3153 // XXX_jblas: We need to fix this so that it removes the document
3154 // base URL, and then prepends with the new page URL.
3155 //if full path exists and is same, chop it - helps IE out
3156 thisUrl = thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' );
3158 if( !/^(\w+:|#|\/)/.test( thisUrl ) ) {
3159 $( this ).attr( thisAttr, newPath + thisUrl );
3164 //append to page and enhance
3165 // TODO taging a page with external to make sure that embedded pages aren't removed
3166 // by the various page handling code is bad. Having page handling code in many
3167 // places is bad. Solutions post 1.0
3169 .attr( "data-" + $.mobile.ns + "url", path.convertUrlToDataUrl( fileUrl ) )
3170 .attr( "data-" + $.mobile.ns + "external-page", true )
3171 .appendTo( settings.pageContainer );
3173 // wait for page creation to leverage options defined on widget
3174 page.one( 'pagecreate', $.mobile._bindPageRemove );
3176 enhancePage( page, settings.role );
3178 // Enhancing the page may result in new dialogs/sub pages being inserted
3179 // into the DOM. If the original absUrl refers to a sub-page, that is the
3180 // real page we are interested in.
3181 if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) {
3182 page = settings.pageContainer.children( ":jqmData(url='" + dataUrl + "')" );
3185 //bind pageHide to removePage after it's hidden, if the page options specify to do so
3187 // Remove loading message.
3188 if ( settings.showLoadMsg ) {
3192 // Add the page reference and xhr to our triggerData.
3193 triggerData.xhr = xhr;
3194 triggerData.textStatus = textStatus;
3195 triggerData.page = page;
3197 // Let listeners know the page loaded successfully.
3198 settings.pageContainer.trigger( "pageload", triggerData );
3200 deferred.resolve( absUrl, options, page, dupCachedPage );
3202 error: function( xhr, textStatus, errorThrown ) {
3203 //set base back to current path
3205 base.set( path.get() );
3208 // Add error info to our triggerData.
3209 triggerData.xhr = xhr;
3210 triggerData.textStatus = textStatus;
3211 triggerData.errorThrown = errorThrown;
3213 var plfEvent = new $.Event( "pageloadfailed" );
3215 // Let listeners know the page load failed.
3216 settings.pageContainer.trigger( plfEvent, triggerData );
3218 // If the default behavior is prevented, stop here!
3219 // Note that it is the responsibility of the listener/handler
3220 // that called preventDefault(), to resolve/reject the
3221 // deferred object within the triggerData.
3222 if( plfEvent.isDefaultPrevented() ){
3226 // Remove loading message.
3227 if ( settings.showLoadMsg ) {
3229 // Remove loading message.
3232 // show error message
3233 $.mobile.showPageLoadingMsg( $.mobile.pageLoadErrorMessageTheme, $.mobile.pageLoadErrorMessage, true );
3236 setTimeout( $.mobile.hidePageLoadingMsg, 1500 );
3239 deferred.reject( absUrl, options );
3244 return deferred.promise();
3247 $.mobile.loadPage.defaults = {
3251 role: undefined, // By default we rely on the role defined by the @data-role attribute.
3253 pageContainer: undefined,
3254 loadMsgDelay: 50 // This delay allows loads that pull from browser cache to occur without showing the loading message.
3257 // Show a specific page in the page container.
3258 $.mobile.changePage = function( toPage, options ) {
3259 // If we are in the midst of a transition, queue the current request.
3260 // We'll call changePage() once we're done with the current transition to
3261 // service the request.
3262 if( isPageTransitioning ) {
3263 pageTransitionQueue.unshift( arguments );
3267 var settings = $.extend( {}, $.mobile.changePage.defaults, options );
3269 // Make sure we have a pageContainer to work with.
3270 settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
3272 // Make sure we have a fromPage.
3273 settings.fromPage = settings.fromPage || $.mobile.activePage;
3275 var mpc = settings.pageContainer,
3276 pbcEvent = new $.Event( "pagebeforechange" ),
3277 triggerData = { toPage: toPage, options: settings };
3279 // Let listeners know we're about to change the current page.
3280 mpc.trigger( pbcEvent, triggerData );
3282 // If the default behavior is prevented, stop here!
3283 if( pbcEvent.isDefaultPrevented() ){
3287 // We allow "pagebeforechange" observers to modify the toPage in the trigger
3288 // data to allow for redirects. Make sure our toPage is updated.
3290 toPage = triggerData.toPage;
3292 // Set the isPageTransitioning flag to prevent any requests from
3293 // entering this method while we are in the midst of loading a page
3294 // or transitioning.
3296 isPageTransitioning = true;
3298 // If the caller passed us a url, call loadPage()
3299 // to make sure it is loaded into the DOM. We'll listen
3300 // to the promise object it returns so we know when
3301 // it is done loading or if an error ocurred.
3302 if ( typeof toPage == "string" ) {
3303 $.mobile.loadPage( toPage, settings )
3304 .done(function( url, options, newPage, dupCachedPage ) {
3305 isPageTransitioning = false;
3306 options.duplicateCachedPage = dupCachedPage;
3307 $.mobile.changePage( newPage, options );
3309 .fail(function( url, options ) {
3310 isPageTransitioning = false;
3312 //clear out the active button state
3313 removeActiveLinkClass( true );
3315 //release transition lock so navigation is free again
3316 releasePageTransitionLock();
3317 settings.pageContainer.trigger( "pagechangefailed", triggerData );
3322 // If we are going to the first-page of the application, we need to make
3323 // sure settings.dataUrl is set to the application document url. This allows
3324 // us to avoid generating a document url with an id hash in the case where the
3325 // first-page of the document has an id attribute specified.
3326 if ( toPage[ 0 ] === $.mobile.firstPage[ 0 ] && !settings.dataUrl ) {
3327 settings.dataUrl = documentUrl.hrefNoHash;
3330 // The caller passed us a real page DOM element. Update our
3331 // internal state and then trigger a transition to the page.
3332 var fromPage = settings.fromPage,
3333 url = ( settings.dataUrl && path.convertUrlToDataUrl( settings.dataUrl ) ) || toPage.jqmData( "url" ),
3334 // The pageUrl var is usually the same as url, except when url is obscured as a dialog url. pageUrl always contains the file path
3336 fileUrl = path.getFilePath( url ),
3337 active = urlHistory.getActive(),
3338 activeIsInitialPage = urlHistory.activeIndex === 0,
3340 pageTitle = document.title,
3341 isDialog = settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog";
3343 // By default, we prevent changePage requests when the fromPage and toPage
3344 // are the same element, but folks that generate content manually/dynamically
3345 // and reuse pages want to be able to transition to the same page. To allow
3346 // this, they will need to change the default value of allowSamePageTransition
3347 // to true, *OR*, pass it in as an option when they manually call changePage().
3348 // It should be noted that our default transition animations assume that the
3349 // formPage and toPage are different elements, so they may behave unexpectedly.
3350 // It is up to the developer that turns on the allowSamePageTransitiona option
3351 // to either turn off transition animations, or make sure that an appropriate
3352 // animation transition is used.
3353 if( fromPage && fromPage[0] === toPage[0] && !settings.allowSamePageTransition ) {
3354 isPageTransitioning = false;
3355 mpc.trigger( "pagechange", triggerData );
3357 // Even if there is no page change to be done, we should keep the urlHistory in sync with the hash changes
3358 if( settings.fromHashChange ) {
3359 urlHistory.directHashChange({
3361 isBack: function() {},
3362 isForward: function() {}
3369 // We need to make sure the page we are given has already been enhanced.
3370 enhancePage( toPage, settings.role );
3372 // If the changePage request was sent from a hashChange event, check to see if the
3373 // page is already within the urlHistory stack. If so, we'll assume the user hit
3374 // the forward/back button and will try to match the transition accordingly.
3375 if( settings.fromHashChange ) {
3376 urlHistory.directHashChange({
3378 isBack: function() { historyDir = -1; },
3379 isForward: function() { historyDir = 1; }
3383 // Kill the keyboard.
3384 // XXX_jblas: We need to stop crawling the entire document to kill focus. Instead,
3385 // we should be tracking focus with a delegate() handler so we already have
3386 // the element in hand at this point.
3387 // Wrap this in a try/catch block since IE9 throw "Unspecified error" if document.activeElement
3388 // is undefined when we are in an IFrame.
3390 if(document.activeElement && document.activeElement.nodeName.toLowerCase() != 'body') {
3391 $(document.activeElement).blur();
3393 $( "input:focus, textarea:focus, select:focus" ).blur();
3397 // Record whether we are at a place in history where a dialog used to be - if so, do not add a new history entry and do not change the hash either
3398 var alreadyThere = false;
3400 // If we're displaying the page as a dialog, we don't want the url
3401 // for the dialog content to be used in the hash. Instead, we want
3402 // to append the dialogHashKey to the url of the current page.
3403 if ( isDialog && active ) {
3404 // on the initial page load active.url is undefined and in that case should
3405 // be an empty string. Moving the undefined -> empty string back into
3406 // urlHistory.addNew seemed imprudent given undefined better represents
3409 // If we are at a place in history that once belonged to a dialog, reuse
3410 // this state without adding to urlHistory and without modifying the hash.
3411 // However, if a dialog is already displayed at this point, and we're
3412 // about to display another dialog, then we must add another hash and
3413 // history entry on top so that one may navigate back to the original dialog
3414 if ( active.url.indexOf( dialogHashKey ) > -1 && !$.mobile.activePage.is( ".ui-dialog" ) ) {
3415 settings.changeHash = false;
3416 alreadyThere = true;
3419 url = ( active.url || "" ) + dialogHashKey;
3421 // tack on another dialogHashKey if this is the same as the initial hash
3422 // this makes sure that a history entry is created for this dialog
3423 if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) {
3424 url += dialogHashKey;
3428 // Set the location hash.
3429 if( settings.changeHash !== false && url ) {
3430 //disable hash listening temporarily
3431 urlHistory.ignoreNextHashChange = true;
3432 //update hash and history
3436 // if title element wasn't found, try the page div data attr too
3437 // If this is a deep-link or a reload ( active === undefined ) then just use pageTitle
3438 var newPageTitle = ( !active )? pageTitle : toPage.jqmData( "title" ) || toPage.children(":jqmData(role='header')").find(".ui-title" ).getEncodedText();
3439 if( !!newPageTitle && pageTitle == document.title ) {
3440 pageTitle = newPageTitle;
3442 if ( !toPage.jqmData( "title" ) ) {
3443 toPage.jqmData( "title", pageTitle );
3446 // Make sure we have a transition defined.
3447 settings.transition = settings.transition
3448 || ( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined )
3449 || ( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition );
3451 //add page to history stack if it's not back or forward
3452 if( !historyDir && !alreadyThere ) {
3453 urlHistory.addNew( url, settings.transition, pageTitle, pageUrl, settings.role );
3457 document.title = urlHistory.getActive().title;
3459 //set "toPage" as activePage
3460 $.mobile.activePage = toPage;
3462 // If we're navigating back in the URL history, set reverse accordingly.
3463 settings.reverse = settings.reverse || historyDir < 0;
3465 transitionPages( toPage, fromPage, settings.transition, settings.reverse )
3466 .done(function( name, reverse, $to, $from, alreadyFocused ) {
3467 removeActiveLinkClass();
3469 //if there's a duplicateCachedPage, remove it from the DOM now that it's hidden
3470 if ( settings.duplicateCachedPage ) {
3471 settings.duplicateCachedPage.remove();
3474 // Send focus to the newly shown page. Moved from promise .done binding in transitionPages
3475 // itself to avoid ie bug that reports offsetWidth as > 0 (core check for visibility)
3476 // despite visibility: hidden addresses issue #2965
3477 // https://github.com/jquery/jquery-mobile/issues/2965
3478 if( !alreadyFocused ){
3479 $.mobile.focusPage( toPage );
3482 releasePageTransitionLock();
3484 // Let listeners know we're all done changing the current page.
3485 mpc.trigger( "pagechange", triggerData );
3489 $.mobile.changePage.defaults = {
3490 transition: undefined,
3493 fromHashChange: false,
3494 role: undefined, // By default we rely on the role defined by the @data-role attribute.
3495 duplicateCachedPage: undefined,
3496 pageContainer: undefined,
3497 showLoadMsg: true, //loading message shows by default when pages are being fetched during changePage
3499 fromPage: undefined,
3500 allowSamePageTransition: false
3503 /* Event Bindings - hashchange, submit, and click */
3504 function findClosestLink( ele )
3507 // Look for the closest element with a nodeName of "a".
3508 // Note that we are checking if we have a valid nodeName
3509 // before attempting to access it. This is because the
3510 // node we get called with could have originated from within
3511 // an embedded SVG document where some symbol instance elements
3512 // don't have nodeName defined on them, or strings are of type
3513 // SVGAnimatedString.
3514 if ( ( typeof ele.nodeName === "string" ) && ele.nodeName.toLowerCase() == "a" ) {
3517 ele = ele.parentNode;
3522 // The base URL for any given element depends on the page it resides in.
3523 function getClosestBaseUrl( ele )
3525 // Find the closest page and extract out its url.
3526 var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ),
3527 base = documentBase.hrefNoHash;
3529 if ( !url || !path.isPath( url ) ) {
3533 return path.makeUrlAbsolute( url, base);
3536 //The following event bindings should be bound after mobileinit has been triggered
3537 //the following deferred is resolved in the init file
3538 $.mobile.navreadyDeferred = $.Deferred();
3539 $.mobile.navreadyDeferred.done( function(){
3540 //bind to form submit events, handle with Ajax
3541 $( document ).delegate( "form", "submit", function( event ) {
3542 var $this = $( this );
3544 if( !$.mobile.ajaxEnabled ||
3545 // test that the form is, itself, ajax false
3546 $this.is(":jqmData(ajax='false')") ||
3547 // test that $.mobile.ignoreContentEnabled is set and
3548 // the form or one of it's parents is ajax=false
3549 !$this.jqmHijackable().length ) {
3553 var type = $this.attr( "method" ),
3554 target = $this.attr( "target" ),
3555 url = $this.attr( "action" );
3557 // If no action is specified, browsers default to using the
3558 // URL of the document containing the form. Since we dynamically
3559 // pull in pages from external documents, the form should submit
3560 // to the URL for the source document of the page containing
3563 // Get the @data-url for the page containing the form.
3564 url = getClosestBaseUrl( $this );
3565 if ( url === documentBase.hrefNoHash ) {
3566 // The url we got back matches the document base,
3567 // which means the page must be an internal/embedded page,
3568 // so default to using the actual document url as a browser
3570 url = documentUrl.hrefNoSearch;
3574 url = path.makeUrlAbsolute( url, getClosestBaseUrl($this) );
3576 if(( path.isExternal( url ) && !path.isPermittedCrossDomainRequest(documentUrl, url)) || target ) {
3580 $.mobile.changePage(
3583 type: type && type.length && type.toLowerCase() || "get",
3584 data: $this.serialize(),
3585 transition: $this.jqmData( "transition" ),
3586 direction: $this.jqmData( "direction" ),
3590 event.preventDefault();
3593 //add active state on vclick
3594 $( document ).bind( "vclick", function( event ) {
3595 // if this isn't a left click we don't care. Its important to note
3596 // that when the virtual event is generated it will create the which attr
3597 if ( event.which > 1 || !$.mobile.linkBindingEnabled ) {
3601 var link = findClosestLink( event.target );
3603 // split from the previous return logic to avoid find closest where possible
3604 // TODO teach $.mobile.hijackable to operate on raw dom elements so the link wrapping
3606 if ( !$(link).jqmHijackable().length ) {
3611 if ( path.parseUrl( link.getAttribute( "href" ) || "#" ).hash !== "#" ) {
3612 removeActiveLinkClass( true );
3613 $activeClickedLink = $( link ).closest( ".ui-btn" ).not( ".ui-disabled" );
3614 $activeClickedLink.addClass( $.mobile.activeBtnClass );
3619 // click routing - direct to HTTP or Ajax, accordingly
3620 $( document ).bind( "click", function( event ) {
3621 if( !$.mobile.linkBindingEnabled ){
3625 var link = findClosestLink( event.target ), $link = $( link ), httpCleanup;
3627 // If there is no link associated with the click or its not a left
3628 // click we want to ignore the click
3629 // TODO teach $.mobile.hijackable to operate on raw dom elements so the link wrapping
3631 if ( !link || event.which > 1 || !$link.jqmHijackable().length ) {
3635 //remove active link class if external (then it won't be there if you come back)
3636 httpCleanup = function(){
3637 window.setTimeout( function() { removeActiveLinkClass( true ); }, 200 );
3640 //if there's a data-rel=back attr, go back in history
3641 if( $link.is( ":jqmData(rel='back')" ) ) {
3642 window.history.back();
3646 var baseUrl = getClosestBaseUrl( $link ),
3648 //get href, if defined, otherwise default to empty hash
3649 href = path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl );
3651 //if ajax is disabled, exit early
3652 if( !$.mobile.ajaxEnabled && !path.isEmbeddedPage( href ) ){
3654 //use default click handling
3658 // XXX_jblas: Ideally links to application pages should be specified as
3659 // an url to the application document with a hash that is either
3660 // the site relative path or id to the page. But some of the
3661 // internal code that dynamically generates sub-pages for nested
3662 // lists and select dialogs, just write a hash in the link they
3663 // create. This means the actual URL path is based on whatever
3664 // the current value of the base tag is at the time this code
3665 // is called. For now we are just assuming that any url with a
3666 // hash in it is an application page reference.
3667 if ( href.search( "#" ) != -1 ) {
3668 href = href.replace( /[^#]*#/, "" );
3670 //link was an empty hash meant purely
3671 //for interaction, so we ignore it.
3672 event.preventDefault();
3674 } else if ( path.isPath( href ) ) {
3675 //we have apath so make it the href we want to load.
3676 href = path.makeUrlAbsolute( href, baseUrl );
3678 //we have a simple id so use the documentUrl as its base.
3679 href = path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash );
3683 // Should we handle this link, or let the browser deal with it?
3684 var useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ),
3686 // Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
3687 // requests if the document doing the request was loaded via the file:// protocol.
3688 // This is usually to allow the application to "phone home" and fetch app specific
3689 // data. We normally let the browser handle external/cross-domain urls, but if the
3690 // allowCrossDomainPages option is true, we will allow cross-domain http/https
3691 // requests to go through our page loading logic.
3693 //check for protocol or rel and its not an embedded page
3694 //TODO overlap in logic from isExternal, rel=external check should be
3695 // moved into more comprehensive isExternalLink
3696 isExternal = useDefaultUrlHandling || ( path.isExternal( href ) && !path.isPermittedCrossDomainRequest(documentUrl, href) );
3700 //use default click handling
3705 var transition = $link.jqmData( "transition" ),
3706 direction = $link.jqmData( "direction" ),
3707 reverse = ( direction && direction === "reverse" ) ||
3708 // deprecated - remove by 1.0
3709 $link.jqmData( "back" ),
3711 //this may need to be more specific as we use data-rel more
3712 role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined;
3714 $.mobile.changePage( href, { transition: transition, reverse: reverse, role: role } );
3715 event.preventDefault();
3718 //prefetch pages when anchors with data-prefetch are encountered
3719 $( document ).delegate( ".ui-page", "pageshow.prefetch", function() {
3721 $( this ).find( "a:jqmData(prefetch)" ).each(function(){
3722 var $link = $(this),
3723 url = $link.attr( "href" );
3725 if ( url && $.inArray( url, urls ) === -1 ) {
3728 $.mobile.loadPage( url, {role: $link.attr("data-" + $.mobile.ns + "rel")} );
3733 $.mobile._handleHashChange = function( hash ) {
3734 //find first page via hash
3735 var to = path.stripHash( hash ),
3736 //transition is false if it's the first page, undefined otherwise (and may be overridden by default)
3737 transition = $.mobile.urlHistory.stack.length === 0 ? "none" : undefined,
3739 // default options for the changPage calls made after examining the current state
3740 // of the page and the hash
3741 changePageOptions = {
3742 transition: transition,
3744 fromHashChange: true
3747 if ( 0 === urlHistory.stack.length ) {
3748 urlHistory.initialDst = to;
3751 //if listening is disabled (either globally or temporarily), or it's a dialog hash
3752 if( !$.mobile.hashListeningEnabled || urlHistory.ignoreNextHashChange ) {
3753 urlHistory.ignoreNextHashChange = false;
3757 // special case for dialogs
3758 if( urlHistory.stack.length > 1 && to.indexOf( dialogHashKey ) > -1 && urlHistory.initialDst !== to ) {
3760 // If current active page is not a dialog skip the dialog and continue
3761 // in the same direction
3762 if(!$.mobile.activePage.is( ".ui-dialog" )) {
3763 //determine if we're heading forward or backward and continue accordingly past
3764 //the current dialog
3765 urlHistory.directHashChange({
3767 isBack: function() { window.history.back(); },
3768 isForward: function() { window.history.forward(); }
3771 // prevent changePage()
3774 // if the current active page is a dialog and we're navigating
3775 // to a dialog use the dialog objected saved in the stack
3776 urlHistory.directHashChange({
3779 // regardless of the direction of the history change
3781 either: function( isBack ) {
3782 var active = $.mobile.urlHistory.getActive();
3784 to = active.pageUrl;
3786 // make sure to set the role, transition and reversal
3787 // as most of this is lost by the domCache cleaning
3788 $.extend( changePageOptions, {
3790 transition: active.transition,
3798 //if to is defined, load it
3800 // At this point, 'to' can be one of 3 things, a cached page element from
3801 // a history stack entry, an id, or site-relative/absolute URL. If 'to' is
3802 // an id, we need to resolve it against the documentBase, not the location.href,
3803 // since the hashchange could've been the result of a forward/backward navigation
3804 // that crosses from an external page/dialog to an internal page/dialog.
3805 to = ( typeof to === "string" && !path.isPath( to ) ) ? ( path.makeUrlAbsolute( '#' + to, documentBase ) ) : to;
3806 $.mobile.changePage( to, changePageOptions );
3808 //there's no hash, go to the first page in the dom
3809 $.mobile.changePage( $.mobile.firstPage, changePageOptions );
3813 //hashchange event handler
3814 $window.bind( "hashchange", function( e, triggered ) {
3815 $.mobile._handleHashChange( location.hash );
3818 //set page min-heights to be device specific
3819 $( document ).bind( "pageshow", resetActivePageHeight );
3820 $( window ).bind( "throttledresize", resetActivePageHeight );
3822 });//navreadyDeferred done callback
3826 ( function( $, window ) {
3827 // For now, let's Monkeypatch this onto the end of $.mobile._registerInternalEvents
3828 // Scope self to pushStateHandler so we can reference it sanely within the
3829 // methods handed off as event handlers
3830 var pushStateHandler = {},
3831 self = pushStateHandler,
3833 url = $.mobile.path.parseUrl( location.href ),
3834 mobileinitDeferred = $.Deferred(),
3835 domreadyDeferred = $.Deferred();
3837 $( document ).ready( $.proxy( domreadyDeferred, "resolve" ) );
3839 $( document ).one( "mobileinit", $.proxy( mobileinitDeferred, "resolve" ) );
3841 $.extend( pushStateHandler, {
3842 // TODO move to a path helper, this is rather common functionality
3843 initialFilePath: (function() {
3844 return url.pathname + url.search;
3847 hashChangeTimeout: 200,
3849 hashChangeEnableTimer: undefined,
3851 initialHref: url.hrefNoHash,
3855 hash: location.hash || "#" + self.initialFilePath,
3856 title: document.title,
3858 // persist across refresh
3859 initialHref: self.initialHref
3863 resetUIKeys: function( url ) {
3864 var dialog = $.mobile.dialogHashKey,
3865 subkey = "&" + $.mobile.subPageUrlKey,
3866 dialogIndex = url.indexOf( dialog );
3868 if( dialogIndex > -1 ) {
3869 url = url.slice( 0, dialogIndex ) + "#" + url.slice( dialogIndex );
3870 } else if( url.indexOf( subkey ) > -1 ) {
3871 url = url.split( subkey ).join( "#" + subkey );
3877 // TODO sort out a single barrier to hashchange functionality
3878 nextHashChangePrevented: function( value ) {
3879 $.mobile.urlHistory.ignoreNextHashChange = value;
3880 self.onHashChangeDisabled = value;
3883 // on hash change we want to clean up the url
3884 // NOTE this takes place *after* the vanilla navigation hash change
3885 // handling has taken place and set the state of the DOM
3886 onHashChange: function( e ) {
3887 // disable this hash change
3888 if( self.onHashChangeDisabled ){
3893 hash = location.hash,
3894 isPath = $.mobile.path.isPath( hash ),
3895 resolutionUrl = isPath ? location.href : $.mobile.getDocumentUrl();
3897 hash = isPath ? hash.replace( "#", "" ) : hash;
3900 // propulate the hash when its not available
3901 state = self.state();
3903 // make the hash abolute with the current href
3904 href = $.mobile.path.makeUrlAbsolute( hash, resolutionUrl );
3907 href = self.resetUIKeys( href );
3910 // replace the current url with the new href and store the state
3911 // Note that in some cases we might be replacing an url with the
3912 // same url. We do this anyways because we need to make sure that
3913 // all of our history entries have a state object associated with
3914 // them. This allows us to work around the case where window.history.back()
3915 // is called to transition from an external page to an embedded page.
3916 // In that particular case, a hashchange event is *NOT* generated by the browser.
3917 // Ensuring each history entry has a state object means that onPopState()
3918 // will always trigger our hashchange callback even when a hashchange event
3920 history.replaceState( state, document.title, href );
3923 // on popstate (ie back or forward) we need to replace the hash that was there previously
3924 // cleaned up by the additional hash handling
3925 onPopState: function( e ) {
3926 var poppedState = e.originalEvent.state,
3927 fromHash, toHash, hashChanged;
3929 // if there's no state its not a popstate we care about, eg chrome's initial popstate
3931 // if we get two pop states in under this.hashChangeTimeout
3932 // make sure to clear any timer set for the previous change
3933 clearTimeout( self.hashChangeEnableTimer );
3935 // make sure to enable hash handling for the the _handleHashChange call
3936 self.nextHashChangePrevented( false );
3938 // change the page based on the hash in the popped state
3939 $.mobile._handleHashChange( poppedState.hash );
3941 // prevent any hashchange in the next self.hashChangeTimeout
3942 self.nextHashChangePrevented( true );
3944 // re-enable hash change handling after swallowing a possible hash
3945 // change event that comes on all popstates courtesy of browsers like Android
3946 self.hashChangeEnableTimer = setTimeout( function() {
3947 self.nextHashChangePrevented( false );
3948 }, self.hashChangeTimeout);
3953 $win.bind( "hashchange", self.onHashChange );
3955 // Handle popstate events the occur through history changes
3956 $win.bind( "popstate", self.onPopState );
3958 // if there's no hash, we need to replacestate for returning to home
3959 if ( location.hash === "" ) {
3960 history.replaceState( self.state(), document.title, location.href );
3965 // We need to init when "mobileinit", "domready", and "navready" have all happened
3966 $.when( domreadyDeferred, mobileinitDeferred, $.mobile.navreadyDeferred ).done( function() {
3967 if( $.mobile.pushStateEnabled && $.support.pushState ){
3968 pushStateHandler.init();
3974 * fallback transition for pop in non-3D supporting browsers (which tend to handle complex transitions poorly in general
3977 (function( $, window, undefined ) {
3979 $.mobile.transitionFallbacks.pop = "fade";
3984 * fallback transition for slide in non-3D supporting browsers (which tend to handle complex transitions poorly in general
3987 (function( $, window, undefined ) {
3989 // Use the simultaneous transition handler for slide transitions
3990 $.mobile.transitionHandlers.slide = $.mobile.transitionHandlers.simultaneous;
3992 // Set the slide transition's fallback to "fade"
3993 $.mobile.transitionFallbacks.slide = "fade";
3998 * fallback transition for slidedown in non-3D supporting browsers (which tend to handle complex transitions poorly in general
4001 (function( $, window, undefined ) {
4003 $.mobile.transitionFallbacks.slidedown = "fade";
4008 * fallback transition for slideup in non-3D supporting browsers (which tend to handle complex transitions poorly in general
4011 (function( $, window, undefined ) {
4013 $.mobile.transitionFallbacks.slideup = "fade";
4018 * fallback transition for flip in non-3D supporting browsers (which tend to handle complex transitions poorly in general
4021 (function( $, window, undefined ) {
4023 $.mobile.transitionFallbacks.flip = "fade";
4028 * fallback transition for flow in non-3D supporting browsers (which tend to handle complex transitions poorly in general
4031 (function( $, window, undefined ) {
4033 $.mobile.transitionFallbacks.flow = "fade";
4038 * fallback transition for turn in non-3D supporting browsers (which tend to handle complex transitions poorly in general
4041 (function( $, window, undefined ) {
4043 $.mobile.transitionFallbacks.turn = "fade";
4047 (function( $, undefined ) {
4049 $.mobile.page.prototype.options.degradeInputs = {
4053 "datetime-local": false,
4066 //auto self-init widgets
4067 $( document ).bind( "pagecreate create", function( e ){
4069 var page = $.mobile.closestPageData($(e.target)), options;
4075 options = page.options;
4077 // degrade inputs to avoid poorly implemented native functionality
4078 $( e.target ).find( "input" ).not( page.keepNativeSelector() ).each(function() {
4079 var $this = $( this ),
4080 type = this.getAttribute( "type" ),
4081 optType = options.degradeInputs[ type ] || "text";
4083 if ( options.degradeInputs[ type ] ) {
4084 var html = $( "<div>" ).html( $this.clone() ).html(),
4085 // In IE browsers, the type sometimes doesn't exist in the cloned markup, so we replace the closing tag instead
4086 hasType = html.indexOf( " type=" ) > -1,
4087 findstr = hasType ? /\s+type=["']?\w+['"]?/ : /\/?>/,
4088 repstr = " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\"" + ( hasType ? "" : ">" );
4090 $this.replaceWith( html.replace( findstr, repstr ) );
4098 (function( $, window, undefined ) {
4100 $.widget( "mobile.dialog", $.mobile.widget, {
4102 closeBtnText : "Close",
4104 initSelector : ":jqmData(role='dialog')"
4106 _create: function() {
4109 headerCloseButton = $( "<a href='#' data-" + $.mobile.ns + "icon='delete' data-" + $.mobile.ns + "iconpos='notext'>"+ this.options.closeBtnText + "</a>" ),
4110 dialogWrap = $("<div/>", {
4112 "class" : "ui-dialog-contain ui-corner-all ui-overlay-shadow"
4115 $el.addClass( "ui-dialog ui-overlay-" + this.options.overlayTheme );
4117 // Class the markup for dialog styling
4120 .wrapInner( dialogWrap )
4122 .find( ":jqmData(role='header')" )
4123 .prepend( headerCloseButton )
4125 .children( ':first-child')
4126 .addClass( "ui-corner-top" )
4128 .children( ":last-child" )
4129 .addClass( "ui-corner-bottom" );
4131 // this must be an anonymous function so that select menu dialogs can replace
4132 // the close method. This is a change from previously just defining data-rel=back
4133 // on the button and letting nav handle it
4135 // Use click rather than vclick in order to prevent the possibility of unintentionally
4136 // reopening the dialog if the dialog opening item was directly under the close button.
4137 headerCloseButton.bind( "click", function() {
4142 - clicks and submits should use the closing transition that the dialog opened with
4143 unless a data-transition is specified on the link/form
4144 - if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally
4146 $el.bind( "vclick submit", function( event ) {
4147 var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ),
4150 if ( $target.length && !$target.jqmData( "transition" ) ) {
4152 active = $.mobile.urlHistory.getActive() || {};
4154 $target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) )
4155 .attr( "data-" + $.mobile.ns + "direction", "reverse" );
4158 .bind( "pagehide", function( e, ui ) {
4159 self._isClosed = false;
4160 $( this ).find( "." + $.mobile.activeBtnClass ).not( ".ui-slider-bg" ).removeClass( $.mobile.activeBtnClass );
4162 // Override the theme set by the page plugin on pageshow
4163 .bind( "pagebeforeshow", function(){
4164 if( self.options.overlayTheme ){
4166 .page( "removeContainerBackground" )
4167 .page( "setContainerBackground", self.options.overlayTheme );
4172 // Close method goes back in history
4174 if ( !this._isClosed ) {
4175 this._isClosed = true;
4176 if ( $.mobile.hashListeningEnabled ) {
4177 window.history.back();
4180 $.mobile.changePage( $.mobile.urlHistory.getPrev().url );
4186 //auto self-init widgets
4187 $( document ).delegate( $.mobile.dialog.prototype.options.initSelector, "pagecreate", function(){
4188 $.mobile.dialog.prototype.enhance( this );
4193 (function( $, undefined ) {
4195 $.mobile.page.prototype.options.backBtnText = "Back";
4196 $.mobile.page.prototype.options.addBackBtn = false;
4197 $.mobile.page.prototype.options.backBtnTheme = null;
4198 $.mobile.page.prototype.options.headerTheme = "a";
4199 $.mobile.page.prototype.options.footerTheme = "a";
4200 $.mobile.page.prototype.options.contentTheme = null;
4202 // NOTE bind used to force this binding to run before the buttonMarkup binding
4203 // which expects .ui-footer top be applied in its gigantic selector
4204 // TODO remove the buttonMarkup giant selector and move it to the various modules
4205 // on which it depends
4206 $( document ).bind( "pagecreate", function( e ) {
4207 var $page = $( e.target ),
4208 o = $page.data( "page" ).options,
4209 pageRole = $page.jqmData( "role" ),
4210 pageTheme = o.theme;
4212 $( ":jqmData(role='header'), :jqmData(role='footer'), :jqmData(role='content')", $page )
4216 var $this = $( this ),
4217 role = $this.jqmData( "role" ),
4218 theme = $this.jqmData( "theme" ),
4219 contentTheme = theme || o.contentTheme || ( pageRole === "dialog" && pageTheme ),
4225 $this.addClass( "ui-" + role );
4227 //apply theming and markup modifications to page,header,content,footer
4228 if ( role === "header" || role === "footer" ) {
4230 var thisTheme = theme || ( role === "header" ? o.headerTheme : o.footerTheme ) || pageTheme;
4234 .addClass( "ui-bar-" + thisTheme )
4236 .attr( "role", role === "header" ? "banner" : "contentinfo" );
4238 if( role === "header") {
4239 // Right,left buttons
4240 $headeranchors = $this.children( "a" );
4241 leftbtn = $headeranchors.hasClass( "ui-btn-left" );
4242 rightbtn = $headeranchors.hasClass( "ui-btn-right" );
4244 leftbtn = leftbtn || $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length;
4246 rightbtn = rightbtn || $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length;
4249 // Auto-add back btn on pages beyond first view
4250 if ( o.addBackBtn &&
4251 role === "header" &&
4252 $( ".ui-page" ).length > 1 &&
4253 $page.jqmData( "url" ) !== $.mobile.path.stripHash( location.hash ) &&
4256 backBtn = $( "<a href='javascript:void(0);' class='ui-btn-left' data-"+ $.mobile.ns +"rel='back' data-"+ $.mobile.ns +"icon='arrow-l'>"+ o.backBtnText +"</a>" )
4257 // If theme is provided, override default inheritance
4258 .attr( "data-"+ $.mobile.ns +"theme", o.backBtnTheme || thisTheme )
4259 .prependTo( $this );
4263 $this.children( "h1, h2, h3, h4, h5, h6" )
4264 .addClass( "ui-title" )
4265 // Regardless of h element number in src, it becomes h1 for the enhanced page
4271 } else if ( role === "content" ) {
4272 if ( contentTheme ) {
4273 $this.addClass( "ui-body-" + ( contentTheme ) );
4277 $this.attr( "role", "main" );
4284 (function( $, undefined ) {
4286 // filter function removes whitespace between label and form element so we can use inline-block (nodeType 3 = text)
4287 $.fn.fieldcontain = function( options ) {
4289 .addClass( "ui-field-contain ui-body ui-br" )
4290 .contents().filter( function() {
4291 return ( this.nodeType === 3 && !/\S/.test( this.nodeValue ) );
4295 //auto self-init widgets
4296 $( document ).bind( "pagecreate create", function( e ){
4297 $( ":jqmData(role='fieldcontain')", e.target ).jqmEnhanceable().fieldcontain();
4302 (function( $, undefined ) {
4304 $.fn.grid = function( options ) {
4305 return this.each(function() {
4307 var $this = $( this ),
4311 $kids = $this.children(),
4312 gridCols = {solo:1, a:2, b:3, c:4, d:5},
4317 if ( $kids.length <= 5 ) {
4318 for ( var letter in gridCols ) {
4319 if ( gridCols[ letter ] === $kids.length ) {
4325 $this.addClass( "ui-grid-duo" );
4328 iterator = gridCols[grid];
4330 $this.addClass( "ui-grid-" + grid );
4332 $kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" );
4334 if ( iterator > 1 ) {
4335 $kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" );
4337 if ( iterator > 2 ) {
4338 $kids.filter( ":nth-child(3n+3)" ).addClass( "ui-block-c" );
4340 if ( iterator > 3 ) {
4341 $kids.filter( ":nth-child(4n+4)" ).addClass( "ui-block-d" );
4343 if ( iterator > 4 ) {
4344 $kids.filter( ":nth-child(5n+5)" ).addClass( "ui-block-e" );
4350 (function( $, undefined ) {
4352 $( document ).bind( "pagecreate create", function( e ){
4353 $( ":jqmData(role='nojs')", e.target ).addClass( "ui-nojs" );
4359 ( function( $, undefined ) {
4361 $.fn.buttonMarkup = function( options ) {
4362 var $workingSet = this;
4364 // Enforce options to be of type string
4365 options = ( options && ( $.type( options ) == "object" ) )? options : {};
4366 for ( var i = 0; i < $workingSet.length; i++ ) {
4367 var el = $workingSet.eq( i ),
4369 o = $.extend( {}, $.fn.buttonMarkup.defaults, {
4370 icon: options.icon !== undefined ? options.icon : el.jqmData( "icon" ),
4371 iconpos: options.iconpos !== undefined ? options.iconpos : el.jqmData( "iconpos" ),
4372 theme: options.theme !== undefined ? options.theme : el.jqmData( "theme" ) || $.mobile.getInheritedTheme( el, "c" ),
4373 inline: options.inline !== undefined ? options.inline : el.jqmData( "inline" ),
4374 shadow: options.shadow !== undefined ? options.shadow : el.jqmData( "shadow" ),
4375 corners: options.corners !== undefined ? options.corners : el.jqmData( "corners" ),
4376 iconshadow: options.iconshadow !== undefined ? options.iconshadow : el.jqmData( "iconshadow" ),
4377 mini: options.mini !== undefined ? options.mini : el.jqmData( "mini" )
4381 innerClass = "ui-btn-inner",
4382 textClass = "ui-btn-text",
4383 buttonClass, iconClass,
4384 // Button inner markup
4390 $.each(o, function(key, value) {
4391 e.setAttribute( "data-" + $.mobile.ns + key, value );
4392 el.jqmData(key, value);
4395 // Check if this element is already enhanced
4396 buttonElements = $.data(((e.tagName === "INPUT" || e.tagName === "BUTTON") ? e.parentNode : e), "buttonElements");
4398 if (buttonElements) {
4399 e = buttonElements.outer;
4401 buttonInner = buttonElements.inner;
4402 buttonText = buttonElements.text;
4403 // We will recreate this icon below
4404 $(buttonElements.icon).remove();
4405 buttonElements.icon = null;
4408 buttonInner = document.createElement( o.wrapperEls );
4409 buttonText = document.createElement( o.wrapperEls );
4411 buttonIcon = o.icon ? document.createElement( "span" ) : null;
4413 if ( attachEvents && !buttonElements) {
4417 // if not, try to find closest theme container
4419 o.theme = $.mobile.getInheritedTheme( el, "c" );
4422 buttonClass = "ui-btn ui-btn-up-" + o.theme;
4423 buttonClass += o.inline ? " ui-btn-inline" : "";
4424 buttonClass += o.shadow ? " ui-shadow" : "";
4425 buttonClass += o.corners ? " ui-btn-corner-all" : "";
4427 if ( o.mini !== undefined ) {
4428 // Used to control styling in headers/footers, where buttons default to `mini` style.
4429 buttonClass += o.mini ? " ui-mini" : " ui-fullsize";
4432 if ( o.inline !== undefined ) {
4433 // Used to control styling in headers/footers, where buttons default to `mini` style.
4434 buttonClass += o.inline === false ? " ui-btn-block" : " ui-btn-inline";
4439 o.icon = "ui-icon-" + o.icon;
4440 o.iconpos = o.iconpos || "left";
4442 iconClass = "ui-icon " + o.icon;
4444 if ( o.iconshadow ) {
4445 iconClass += " ui-icon-shadow";
4450 buttonClass += " ui-btn-icon-" + o.iconpos;
4452 if ( o.iconpos == "notext" && !el.attr( "title" ) ) {
4453 el.attr( "title", el.getEncodedText() );
4457 innerClass += o.corners ? " ui-btn-corner-all" : "";
4459 if ( o.iconpos && o.iconpos === "notext" && !el.attr( "title" ) ) {
4460 el.attr( "title", el.getEncodedText() );
4463 if ( buttonElements ) {
4464 el.removeClass( buttonElements.bcls || "" );
4466 el.removeClass( "ui-link" ).addClass( buttonClass );
4468 buttonInner.className = innerClass;
4470 buttonText.className = textClass;
4471 if ( !buttonElements ) {
4472 buttonInner.appendChild( buttonText );
4475 buttonIcon.className = iconClass;
4476 if ( !(buttonElements && buttonElements.icon) ) {
4477 buttonIcon.appendChild( document.createTextNode("\u00a0") );
4478 buttonInner.appendChild( buttonIcon );
4482 while ( e.firstChild && !buttonElements) {
4483 buttonText.appendChild( e.firstChild );
4486 if ( !buttonElements ) {
4487 e.appendChild( buttonInner );
4490 // Assign a structure containing the elements of this button to the elements of this button. This
4491 // will allow us to recognize this as an already-enhanced button in future calls to buttonMarkup().
4495 inner : buttonInner,
4500 $.data(e, 'buttonElements', buttonElements);
4501 $.data(buttonInner, 'buttonElements', buttonElements);
4502 $.data(buttonText, 'buttonElements', buttonElements);
4504 $.data(buttonIcon, 'buttonElements', buttonElements);
4511 $.fn.buttonMarkup.defaults = {
4518 function closestEnabledButton( element ) {
4522 // Note that we check for typeof className below because the element we
4523 // handed could be in an SVG DOM where className on SVG elements is defined to
4524 // be of a different type (SVGAnimatedString). We only operate on HTML DOM
4525 // elements, so we look for plain "string".
4526 cname = ( typeof element.className === 'string' ) && (element.className + ' ');
4527 if ( cname && cname.indexOf("ui-btn ") > -1 && cname.indexOf("ui-disabled ") < 0 ) {
4531 element = element.parentNode;
4537 var attachEvents = function() {
4538 var hoverDelay = $.mobile.buttonMarkup.hoverDelay, hov, foc;
4540 $( document ).bind( {
4541 "vmousedown vmousecancel vmouseup vmouseover vmouseout focus blur scrollstart": function( event ) {
4543 $btn = $( closestEnabledButton( event.target ) ),
4546 if ( $btn.length ) {
4547 theme = $btn.attr( "data-" + $.mobile.ns + "theme" );
4549 if ( evt === "vmousedown" ) {
4550 if ( $.support.touch ) {
4551 hov = setTimeout(function() {
4552 $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-down-" + theme );
4555 $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-down-" + theme );
4557 } else if ( evt === "vmousecancel" || evt === "vmouseup" ) {
4558 $btn.removeClass( "ui-btn-down-" + theme ).addClass( "ui-btn-up-" + theme );
4559 } else if ( evt === "vmouseover" || evt === "focus" ) {
4560 if ( $.support.touch ) {
4561 foc = setTimeout(function() {
4562 $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-hover-" + theme );
4565 $btn.removeClass( "ui-btn-up-" + theme ).addClass( "ui-btn-hover-" + theme );
4567 } else if ( evt === "vmouseout" || evt === "blur" || evt === "scrollstart" ) {
4568 $btn.removeClass( "ui-btn-hover-" + theme + " ui-btn-down-" + theme ).addClass( "ui-btn-up-" + theme );
4570 clearTimeout( hov );
4573 clearTimeout( foc );
4578 "focusin focus": function( event ){
4579 $( closestEnabledButton( event.target ) ).addClass( $.mobile.focusClass );
4581 "focusout blur": function( event ){
4582 $( closestEnabledButton( event.target ) ).removeClass( $.mobile.focusClass );
4586 attachEvents = null;
4589 //links in bars, or those with data-role become buttons
4590 //auto self-init widgets
4591 $( document ).bind( "pagecreate create", function( e ){
4593 $( ":jqmData(role='button'), .ui-bar > a, .ui-header > a, .ui-footer > a, .ui-bar > :jqmData(role='controlgroup') > a", e.target )
4594 .not( ".ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" )
4601 (function( $, undefined ) {
4603 $.widget( "mobile.collapsible", $.mobile.widget, {
4605 expandCueText: " click to expand contents",
4606 collapseCueText: " click to collapse contents",
4608 heading: "h1,h2,h3,h4,h5,h6,legend",
4613 initSelector: ":jqmData(role='collapsible')"
4615 _create: function() {
4617 var $el = this.element,
4619 collapsible = $el.addClass( "ui-collapsible" ),
4620 collapsibleHeading = $el.children( o.heading ).first(),
4621 collapsibleContent = collapsible.wrapInner( "<div class='ui-collapsible-content'></div>" ).find( ".ui-collapsible-content" ),
4622 collapsibleSet = $el.closest( ":jqmData(role='collapsible-set')" ).addClass( "ui-collapsible-set" );
4624 // Replace collapsibleHeading if it's a legend
4625 if ( collapsibleHeading.is( "legend" ) ) {
4626 collapsibleHeading = $( "<div role='heading'>"+ collapsibleHeading.html() +"</div>" ).insertBefore( collapsibleHeading );
4627 collapsibleHeading.next().remove();
4630 // If we are in a collapsible set
4631 if ( collapsibleSet.length ) {
4632 // Inherit the theme from collapsible-set
4634 o.theme = collapsibleSet.jqmData("theme") || $.mobile.getInheritedTheme( collapsibleSet, "c" );
4636 // Inherit the content-theme from collapsible-set
4637 if ( !o.contentTheme ) {
4638 o.contentTheme = collapsibleSet.jqmData( "content-theme" );
4641 // Gets the preference icon position in the set
4643 o.iconPos = collapsibleSet.jqmData( "iconpos" );
4647 o.mini = collapsibleSet.jqmData( "mini" );
4650 collapsibleContent.addClass( ( o.contentTheme ) ? ( "ui-body-" + o.contentTheme ) : "");
4653 //drop heading in before content
4654 .insertBefore( collapsibleContent )
4655 //modify markup & attributes
4656 .addClass( "ui-collapsible-heading" )
4657 .append( "<span class='ui-collapsible-heading-status'></span>" )
4658 .wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" )
4664 iconpos: $el.jqmData( "iconpos" ) || o.iconPos || "left",
4669 .add( ".ui-btn-inner", $el )
4670 .addClass( "ui-corner-top ui-corner-bottom" );
4674 .bind( "expand collapse", function( event ) {
4675 if ( !event.isDefaultPrevented() ) {
4677 event.preventDefault();
4679 var $this = $( this ),
4680 isCollapse = ( event.type === "collapse" ),
4681 contentTheme = o.contentTheme;
4684 .toggleClass( "ui-collapsible-heading-collapsed", isCollapse)
4685 .find( ".ui-collapsible-heading-status" )
4686 .text( isCollapse ? o.expandCueText : o.collapseCueText )
4689 .toggleClass( "ui-icon-minus", !isCollapse )
4690 .toggleClass( "ui-icon-plus", isCollapse )
4692 .find( "a" ).first().removeClass( $.mobile.activeBtnClass );
4694 $this.toggleClass( "ui-collapsible-collapsed", isCollapse );
4695 collapsibleContent.toggleClass( "ui-collapsible-content-collapsed", isCollapse ).attr( "aria-hidden", isCollapse );
4697 if ( contentTheme && ( !collapsibleSet.length || collapsible.jqmData( "collapsible-last" ) ) ) {
4699 .find( "a" ).first().add( collapsibleHeading.find( ".ui-btn-inner" ) )
4700 .toggleClass( "ui-corner-bottom", isCollapse );
4701 collapsibleContent.toggleClass( "ui-corner-bottom", !isCollapse );
4703 collapsibleContent.trigger( "updatelayout" );
4706 .trigger( o.collapsed ? "collapse" : "expand" );
4709 .bind( "tap", function( event ) {
4710 collapsibleHeading.find( "a" ).first().addClass( $.mobile.activeBtnClass );
4712 .bind( "click", function( event ) {
4714 var type = collapsibleHeading.is( ".ui-collapsible-heading-collapsed" ) ?
4715 "expand" : "collapse";
4717 collapsible.trigger( type );
4719 event.preventDefault();
4720 event.stopPropagation();
4725 //auto self-init widgets
4726 $( document ).bind( "pagecreate create", function( e ){
4727 $.mobile.collapsible.prototype.enhanceWithin( e.target );
4732 (function( $, undefined ) {
4734 $.widget( "mobile.collapsibleset", $.mobile.widget, {
4736 initSelector: ":jqmData(role='collapsible-set')"
4738 _create: function() {
4739 var $el = this.element.addClass( "ui-collapsible-set" ),
4742 // Inherit the theme from collapsible-set
4744 o.theme = $.mobile.getInheritedTheme( $el, "c" );
4746 // Inherit the content-theme from collapsible-set
4747 if ( !o.contentTheme ) {
4748 o.contentTheme = $el.jqmData( "content-theme" );
4752 o.corners = $el.jqmData( "corners" ) === undefined ? true : false;
4755 // Initialize the collapsible set if it's not already initialized
4756 if ( !$el.jqmData( "collapsiblebound" ) ) {
4758 .jqmData( "collapsiblebound", true )
4759 .bind( "expand collapse", function( event ) {
4760 var isCollapse = ( event.type === "collapse" ),
4761 collapsible = $( event.target ).closest( ".ui-collapsible" ),
4762 widget = collapsible.data( "collapsible" ),
4763 contentTheme = widget.options.contentTheme;
4764 if ( contentTheme && collapsible.jqmData( "collapsible-last" ) ) {
4765 collapsible.find( widget.options.heading ).first()
4766 .find( "a" ).first()
4767 .toggleClass( "ui-corner-bottom", isCollapse )
4768 .find( ".ui-btn-inner" )
4769 .toggleClass( "ui-corner-bottom", isCollapse );
4770 collapsible.find( ".ui-collapsible-content" ).toggleClass( "ui-corner-bottom", !isCollapse );
4773 .bind( "expand", function( event ) {
4775 .closest( ".ui-collapsible" )
4776 .siblings( ".ui-collapsible" )
4777 .trigger( "collapse" );
4786 refresh: function() {
4787 var $el = this.element,
4789 collapsiblesInSet = $el.children( ":jqmData(role='collapsible')" );
4791 $.mobile.collapsible.prototype.enhance( collapsiblesInSet.not( ".ui-collapsible" ) );
4794 collapsiblesInSet.each( function() {
4795 $( this ).find( $.mobile.collapsible.prototype.options.heading )
4796 .find( "a" ).first()
4797 .removeClass( "ui-corner-top ui-corner-bottom" )
4798 .find( ".ui-btn-inner" )
4799 .removeClass( "ui-corner-top ui-corner-bottom" );
4802 collapsiblesInSet.first()
4805 .addClass( o.corners ? "ui-corner-top" : "" )
4806 .find( ".ui-btn-inner" )
4807 .addClass( "ui-corner-top" );
4809 collapsiblesInSet.last()
4810 .jqmData( "collapsible-last", true )
4813 .addClass( o.corners ? "ui-corner-bottom" : "" )
4814 .find( ".ui-btn-inner" )
4815 .addClass( "ui-corner-bottom" );
4819 //auto self-init widgets
4820 $( document ).bind( "pagecreate create", function( e ){
4821 $.mobile.collapsibleset.prototype.enhanceWithin( e.target );
4826 (function( $, undefined ) {
4828 $.widget( "mobile.navbar", $.mobile.widget, {
4832 initSelector: ":jqmData(role='navbar')"
4835 _create: function(){
4837 var $navbar = this.element,
4838 $navbtns = $navbar.find( "a" ),
4839 iconpos = $navbtns.filter( ":jqmData(icon)" ).length ?
4840 this.options.iconpos : undefined;
4842 $navbar.addClass( "ui-navbar ui-mini" )
4843 .attr( "role","navigation" )
4846 .grid({ grid: this.options.grid });
4848 $navbtns.buttonMarkup({
4855 $navbar.delegate( "a", "vclick", function( event ) {
4856 if( !$(event.target).hasClass("ui-disabled") ) {
4857 $navbtns.removeClass( $.mobile.activeBtnClass );
4858 $( this ).addClass( $.mobile.activeBtnClass );
4862 // Buttons in the navbar with ui-state-persist class should regain their active state before page show
4863 $navbar.closest( ".ui-page" ).bind( "pagebeforeshow", function() {
4864 $navbtns.filter( ".ui-state-persist" ).addClass( $.mobile.activeBtnClass );
4869 //auto self-init widgets
4870 $( document ).bind( "pagecreate create", function( e ){
4871 $.mobile.navbar.prototype.enhanceWithin( e.target );
4876 (function( $, undefined ) {
4878 //Keeps track of the number of lists per page UID
4879 //This allows support for multiple nested list in the same page
4880 //https://github.com/jquery/jquery-mobile/issues/1617
4881 var listCountPerPage = {};
4883 $.widget( "mobile.listview", $.mobile.widget, {
4890 splitIcon: "arrow-r",
4893 initSelector: ":jqmData(role='listview')"
4896 _create: function() {
4898 listviewClasses = "";
4900 listviewClasses += t.options.inset ? " ui-listview-inset ui-corner-all ui-shadow " : "";
4902 // create listview markup
4903 t.element.addClass(function( i, orig ) {
4904 return orig + " ui-listview " + listviewClasses;
4910 _removeCorners: function( li, which ) {
4911 var top = "ui-corner-top ui-corner-tr ui-corner-tl",
4912 bot = "ui-corner-bottom ui-corner-br ui-corner-bl";
4914 li = li.add( li.find( ".ui-btn-inner, .ui-li-link-alt, .ui-li-thumb" ) );
4916 if ( which === "top" ) {
4917 li.removeClass( top );
4918 } else if ( which === "bottom" ) {
4919 li.removeClass( bot );
4921 li.removeClass( top + " " + bot );
4925 _refreshCorners: function( create ) {
4931 if ( this.options.inset ) {
4932 $li = this.element.children( "li" );
4933 // at create time the li are not visible yet so we need to rely on .ui-screen-hidden
4934 $visibleli = create?$li.not( ".ui-screen-hidden" ):$li.filter( ":visible" );
4936 this._removeCorners( $li );
4938 // Select the first visible li element
4939 $topli = $visibleli.first()
4940 .addClass( "ui-corner-top" );
4942 $topli.add( $topli.find( ".ui-btn-inner" )
4943 .not( ".ui-li-link-alt span:first-child" ) )
4944 .addClass( "ui-corner-top" )
4946 .find( ".ui-li-link-alt, .ui-li-link-alt span:first-child" )
4947 .addClass( "ui-corner-tr" )
4949 .find( ".ui-li-thumb" )
4951 .addClass( "ui-corner-tl" );
4953 // Select the last visible li element
4954 $bottomli = $visibleli.last()
4955 .addClass( "ui-corner-bottom" );
4957 $bottomli.add( $bottomli.find( ".ui-btn-inner" ) )
4958 .find( ".ui-li-link-alt" )
4959 .addClass( "ui-corner-br" )
4961 .find( ".ui-li-thumb" )
4963 .addClass( "ui-corner-bl" );
4966 this.element.trigger( "updatelayout" );
4970 // This is a generic utility method for finding the first
4971 // node with a given nodeName. It uses basic DOM traversal
4972 // to be fast and is meant to be a substitute for simple
4973 // $.fn.closest() and $.fn.children() calls on a single
4974 // element. Note that callers must pass both the lowerCase
4975 // and upperCase version of the nodeName they are looking for.
4976 // The main reason for this is that this function will be
4977 // called many times and we want to avoid having to lowercase
4978 // the nodeName from the element every time to ensure we have
4979 // a match. Note that this function lives here for now, but may
4980 // be moved into $.mobile if other components need a similar method.
4981 _findFirstElementByTagName: function( ele, nextProp, lcName, ucName )
4984 dict[ lcName ] = dict[ ucName ] = true;
4986 if ( dict[ ele.nodeName ] ) {
4989 ele = ele[ nextProp ];
4993 _getChildrenByTagName: function( ele, lcName, ucName )
4997 dict[ lcName ] = dict[ ucName ] = true;
4998 ele = ele.firstChild;
5000 if ( dict[ ele.nodeName ] ) {
5001 results.push( ele );
5003 ele = ele.nextSibling;
5005 return $( results );
5008 _addThumbClasses: function( containers )
5010 var i, img, len = containers.length;
5011 for ( i = 0; i < len; i++ ) {
5012 img = $( this._findFirstElementByTagName( containers[ i ].firstChild, "nextSibling", "img", "IMG" ) );
5014 img.addClass( "ui-li-thumb" );
5015 $( this._findFirstElementByTagName( img[ 0 ].parentNode, "parentNode", "li", "LI" ) ).addClass( img.is( ".ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" );
5020 refresh: function( create ) {
5021 this.parentPage = this.element.closest( ".ui-page" );
5022 this._createSubPages();
5024 var o = this.options,
5025 $list = this.element,
5027 dividertheme = $list.jqmData( "dividertheme" ) || o.dividerTheme,
5028 listsplittheme = $list.jqmData( "splittheme" ),
5029 listspliticon = $list.jqmData( "spliticon" ),
5030 li = this._getChildrenByTagName( $list[ 0 ], "li", "LI" ),
5031 counter = $.support.cssPseudoElement || !$.nodeName( $list[ 0 ], "ol" ) ? 0 : 1,
5033 item, itemClass, itemTheme,
5034 a, last, splittheme, countParent, icon, imgParents, img, linkIcon;
5037 $list.find( ".ui-li-dec" ).remove();
5041 o.theme = $.mobile.getInheritedTheme( this.element, "c" );
5044 for ( var pos = 0, numli = li.length; pos < numli; pos++ ) {
5045 item = li.eq( pos );
5046 itemClass = "ui-li";
5048 // If we're creating the element, we update it regardless
5049 if ( create || !item.hasClass( "ui-li" ) ) {
5050 itemTheme = item.jqmData("theme") || o.theme;
5051 a = this._getChildrenByTagName( item[ 0 ], "a", "A" );
5052 var isDivider = ( item.jqmData( "role" ) === "list-divider" );
5054 if ( a.length && !isDivider ) {
5055 icon = item.jqmData("icon");
5062 icon: a.length > 1 || icon === false ? false : icon || "arrow-r",
5066 if ( ( icon != false ) && ( a.length == 1 ) ) {
5067 item.addClass( "ui-li-has-arrow" );
5070 a.first().removeClass( "ui-link" ).addClass( "ui-link-inherit" );
5072 if ( a.length > 1 ) {
5073 itemClass += " ui-li-has-alt";
5076 splittheme = listsplittheme || last.jqmData( "theme" ) || o.splitTheme;
5077 linkIcon = last.jqmData("icon");
5080 .attr( "title", last.getEncodedText() )
5081 .addClass( "ui-li-link-alt" )
5090 .find( ".ui-btn-inner" )
5092 $( document.createElement( "span" ) ).buttonMarkup({
5097 // link icon overrides list item icon overrides ul element overrides options
5098 icon: linkIcon || icon || listspliticon || o.splitIcon
5102 } else if ( isDivider ) {
5104 itemClass += " ui-li-divider ui-bar-" + dividertheme;
5105 item.attr( "role", "heading" );
5107 //reset counter when a divider heading is encountered
5113 itemClass += " ui-li-static ui-body-" + itemTheme;
5117 if ( counter && itemClass.indexOf( "ui-li-divider" ) < 0 ) {
5118 countParent = item.is( ".ui-li-static:first" ) ? item : item.find( ".ui-link-inherit" );
5120 countParent.addClass( "ui-li-jsnumbering" )
5121 .prepend( "<span class='ui-li-dec'>" + (counter++) + ". </span>" );
5124 // Instead of setting item class directly on the list item and its
5125 // btn-inner at this point in time, push the item into a dictionary
5126 // that tells us what class to set on it so we can do this after this
5127 // processing loop is finished.
5129 if ( !itemClassDict[ itemClass ] ) {
5130 itemClassDict[ itemClass ] = [];
5133 itemClassDict[ itemClass ].push( item[ 0 ] );
5136 // Set the appropriate listview item classes on each list item
5137 // and their btn-inner elements. The main reason we didn't do this
5138 // in the for-loop above is because we can eliminate per-item function overhead
5139 // by calling addClass() and children() once or twice afterwards. This
5140 // can give us a significant boost on platforms like WP7.5.
5142 for ( itemClass in itemClassDict ) {
5143 $( itemClassDict[ itemClass ] ).addClass( itemClass ).children( ".ui-btn-inner" ).addClass( itemClass );
5146 $list.find( "h1, h2, h3, h4, h5, h6" ).addClass( "ui-li-heading" )
5149 .find( "p, dl" ).addClass( "ui-li-desc" )
5152 .find( ".ui-li-aside" ).each(function() {
5153 var $this = $(this);
5154 $this.prependTo( $this.parent() ); //shift aside to front for css float
5158 .find( ".ui-li-count" ).each( function() {
5159 $( this ).closest( "li" ).addClass( "ui-li-has-count" );
5160 }).addClass( "ui-btn-up-" + ( $list.jqmData( "counttheme" ) || this.options.countTheme) + " ui-btn-corner-all" );
5162 // The idea here is to look at the first image in the list item
5163 // itself, and any .ui-link-inherit element it may contain, so we
5164 // can place the appropriate classes on the image and list item.
5165 // Note that we used to use something like:
5167 // li.find(">img:eq(0), .ui-link-inherit>img:eq(0)").each( ... );
5169 // But executing a find() like that on Windows Phone 7.5 took a
5170 // really long time. Walking things manually with the code below
5171 // allows the 400 listview item page to load in about 3 seconds as
5172 // opposed to 30 seconds.
5174 this._addThumbClasses( li );
5175 this._addThumbClasses( $list.find( ".ui-link-inherit" ) );
5177 this._refreshCorners( create );
5180 //create a string for ID/subpage url creation
5181 _idStringEscape: function( str ) {
5182 return str.replace(/[^a-zA-Z0-9]/g, '-');
5185 _createSubPages: function() {
5186 var parentList = this.element,
5187 parentPage = parentList.closest( ".ui-page" ),
5188 parentUrl = parentPage.jqmData( "url" ),
5189 parentId = parentUrl || parentPage[ 0 ][ $.expando ],
5190 parentListId = parentList.attr( "id" ),
5192 dns = "data-" + $.mobile.ns,
5194 persistentFooterID = parentPage.find( ":jqmData(role='footer')" ).jqmData( "id" ),
5197 if ( typeof listCountPerPage[ parentId ] === "undefined" ) {
5198 listCountPerPage[ parentId ] = -1;
5201 parentListId = parentListId || ++listCountPerPage[ parentId ];
5203 $( parentList.find( "li>ul, li>ol" ).toArray().reverse() ).each(function( i ) {
5206 listId = list.attr( "id" ) || parentListId + "-" + i,
5207 parent = list.parent(),
5208 nodeEls = $( list.prevAll().toArray().reverse() ),
5209 nodeEls = nodeEls.length ? nodeEls : $( "<span>" + $.trim(parent.contents()[ 0 ].nodeValue) + "</span>" ),
5210 title = nodeEls.first().getEncodedText(),//url limits to first 30 chars of text
5211 id = ( parentUrl || "" ) + "&" + $.mobile.subPageUrlKey + "=" + listId,
5212 theme = list.jqmData( "theme" ) || o.theme,
5213 countTheme = list.jqmData( "counttheme" ) || parentList.jqmData( "counttheme" ) || o.countTheme,
5216 //define hasSubPages for use in later removal
5219 newPage = list.detach()
5220 .wrap( "<div " + dns + "role='page' " + dns + "url='" + id + "' " + dns + "theme='" + theme + "' " + dns + "count-theme='" + countTheme + "'><div " + dns + "role='content'></div></div>" )
5222 .before( "<div " + dns + "role='header' " + dns + "theme='" + o.headerTheme + "'><div class='ui-title'>" + title + "</div></div>" )
5223 .after( persistentFooterID ? $( "<div " + dns + "role='footer' " + dns + "id='"+ persistentFooterID +"'>") : "" )
5225 .appendTo( $.mobile.pageContainer );
5229 anchor = parent.find('a:first');
5231 if ( !anchor.length ) {
5232 anchor = $( "<a/>" ).html( nodeEls || title ).prependTo( parent.empty() );
5235 anchor.attr( "href", "#" + id );
5239 // on pagehide, remove any nested pages along with the parent page, as long as they aren't active
5240 // and aren't embedded
5242 parentPage.is( ":jqmData(external-page='true')" ) &&
5243 parentPage.data("page").options.domCache === false ) {
5245 var newRemove = function( e, ui ){
5246 var nextPage = ui.nextPage, npURL,
5247 prEvent = new $.Event( "pageremove" );
5250 npURL = nextPage.jqmData( "url" );
5251 if( npURL.indexOf( parentUrl + "&" + $.mobile.subPageUrlKey ) !== 0 ){
5252 self.childPages().remove();
5253 parentPage.trigger( prEvent );
5254 if( !prEvent.isDefaultPrevented() ){
5255 parentPage.removeWithDependents();
5261 // unbind the original page remove and replace with our specialized version
5263 .unbind( "pagehide.remove" )
5264 .bind( "pagehide.remove", newRemove);
5268 // TODO sort out a better way to track sub pages of the listview this is brittle
5269 childPages: function(){
5270 var parentUrl = this.parentPage.jqmData( "url" );
5272 return $( ":jqmData(url^='"+ parentUrl + "&" + $.mobile.subPageUrlKey +"')");
5276 //auto self-init widgets
5277 $( document ).bind( "pagecreate create", function( e ){
5278 $.mobile.listview.prototype.enhanceWithin( e.target );
5284 * "checkboxradio" plugin
5287 (function( $, undefined ) {
5289 $.widget( "mobile.checkboxradio", $.mobile.widget, {
5292 initSelector: "input[type='checkbox'],input[type='radio']"
5294 _create: function() {
5296 input = this.element,
5297 inheritAttr = function( input, dataAttr ) {
5298 return input.jqmData( dataAttr ) || input.closest( "form,fieldset" ).jqmData( dataAttr )
5300 // NOTE: Windows Phone could not find the label through a selector
5301 // filter works though.
5302 parentLabel = $( input ).closest( "label" ),
5303 label = parentLabel.length ? parentLabel : $( input ).closest( "form,fieldset,:jqmData(role='page'),:jqmData(role='dialog')" ).find( "label" ).filter( "[for='" + input[0].id + "']" ),
5304 inputtype = input[0].type,
5305 mini = inheritAttr( input, "mini" ),
5306 checkedState = inputtype + "-on",
5307 uncheckedState = inputtype + "-off",
5308 icon = input.parents( ":jqmData(type='horizontal')" ).length ? undefined : uncheckedState,
5309 iconpos = inheritAttr( input, "iconpos" ),
5310 activeBtn = icon ? "" : " " + $.mobile.activeBtnClass,
5311 checkedClass = "ui-" + checkedState + activeBtn,
5312 uncheckedClass = "ui-" + uncheckedState,
5313 checkedicon = "ui-icon-" + checkedState,
5314 uncheckedicon = "ui-icon-" + uncheckedState;
5316 if ( inputtype !== "checkbox" && inputtype !== "radio" ) {
5320 // Expose for other methods
5323 inputtype: inputtype,
5324 checkedClass: checkedClass,
5325 uncheckedClass: uncheckedClass,
5326 checkedicon: checkedicon,
5327 uncheckedicon: uncheckedicon
5330 // If there's no selected theme check the data attr
5331 if( !this.options.theme ) {
5332 this.options.theme = $.mobile.getInheritedTheme( this.element, "c" );
5335 label.buttonMarkup({
5336 theme: this.options.theme,
5343 // Wrap the input + label in a div
5344 var wrapper = document.createElement('div');
5345 wrapper.className = 'ui-' + inputtype;
5347 input.add( label ).wrapAll( wrapper );
5350 vmouseover: function( event ) {
5351 if ( $( this ).parent().is( ".ui-disabled" ) ) {
5352 event.stopPropagation();
5356 vclick: function( event ) {
5357 if ( input.is( ":disabled" ) ) {
5358 event.preventDefault();
5364 input.prop( "checked", inputtype === "radio" && true || !input.prop( "checked" ) );
5366 // trigger click handler's bound directly to the input as a substitute for
5367 // how label clicks behave normally in the browsers
5368 // TODO: it would be nice to let the browser's handle the clicks and pass them
5369 // through to the associate input. we can swallow that click at the parent
5370 // wrapper element level
5371 input.triggerHandler( 'click' );
5373 // Input set for common radio buttons will contain all the radio
5374 // buttons, but will not for checkboxes. clearing the checked status
5375 // of other radios ensures the active button state is applied properly
5376 self._getInputSet().not( input ).prop( "checked", false );
5385 vmousedown: function() {
5389 vclick: function() {
5390 var $this = $(this);
5392 // Adds checked attribute to checked input when keyboard is used
5393 if ( $this.is( ":checked" ) ) {
5395 $this.prop( "checked", true);
5396 self._getInputSet().not($this).prop( "checked", false );
5399 $this.prop( "checked", false );
5406 label.addClass( $.mobile.focusClass );
5410 label.removeClass( $.mobile.focusClass );
5417 _cacheVals: function() {
5418 this._getInputSet().each(function() {
5419 $(this).jqmData( "cacheVal", this.checked );
5423 //returns either a set of radios with the same name attribute, or a single checkbox
5424 _getInputSet: function(){
5425 if(this.inputtype === "checkbox") {
5426 return this.element;
5429 return this.element.closest( "form,fieldset,:jqmData(role='page')" )
5430 .find( "input[name='"+ this.element[0].name +"'][type='"+ this.inputtype +"']" );
5433 _updateAll: function() {
5436 this._getInputSet().each(function() {
5437 var $this = $(this);
5439 if ( this.checked || self.inputtype === "checkbox" ) {
5440 $this.trigger( "change" );
5443 .checkboxradio( "refresh" );
5446 refresh: function() {
5447 var input = this.element[0],
5449 icon = label.find( ".ui-icon" );
5451 if ( input.checked ) {
5452 label.addClass( this.checkedClass ).removeClass( this.uncheckedClass );
5453 icon.addClass( this.checkedicon ).removeClass( this.uncheckedicon );
5455 label.removeClass( this.checkedClass ).addClass( this.uncheckedClass );
5456 icon.removeClass( this.checkedicon ).addClass( this.uncheckedicon );
5459 if ( input.disabled ) {
5466 disable: function() {
5467 this.element.prop( "disabled", true ).parent().addClass( "ui-disabled" );
5470 enable: function() {
5471 this.element.prop( "disabled", false ).parent().removeClass( "ui-disabled" );
5475 //auto self-init widgets
5476 $( document ).bind( "pagecreate create", function( e ){
5477 $.mobile.checkboxradio.prototype.enhanceWithin( e.target, true );
5482 (function( $, undefined ) {
5484 $.widget( "mobile.button", $.mobile.widget, {
5493 initSelector: "button, [type='button'], [type='submit'], [type='reset'], [type='image']",
5496 _create: function() {
5497 var $el = this.element,
5505 // if this is a link, check if it's been enhanced and, if not, use the right function
5506 if( $el[ 0 ].tagName === "A" ) {
5507 !$el.hasClass( "ui-btn" ) && $el.buttonMarkup();
5511 // get the inherited theme
5512 // TODO centralize for all widgets
5513 if ( !this.options.theme ) {
5514 this.options.theme = $.mobile.getInheritedTheme( this.element, "c" );
5517 // TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
5518 /* if( $el[0].className.length ) {
5519 classes = $el[0].className;
5521 if( !!~$el[0].className.indexOf( "ui-btn-left" ) ) {
5522 classes = "ui-btn-left";
5525 if( !!~$el[0].className.indexOf( "ui-btn-right" ) ) {
5526 classes = "ui-btn-right";
5529 if( $el.attr( "type" ) === "submit" || $el.attr( "type" ) === "reset" ) {
5530 classes ? classes += " ui-submit" : classes = "ui-submit";
5533 $( "label[for='" + $el.attr( "id" ) + "']" ).addClass( "ui-submit" );
5536 this.button = $( "<div></div>" )
5537 .text( $el.text() || $el.val() )
5538 .insertBefore( $el )
5546 iconshadow: o.iconshadow,
5549 .addClass( classes )
5550 .append( $el.addClass( "ui-btn-hidden" ) );
5552 $button = this.button;
5553 type = $el.attr( "type" );
5554 name = $el.attr( "name" );
5556 // Add hidden input during submit if input type="submit" has a name.
5557 if ( type !== "button" && type !== "reset" && name ) {
5558 $el.bind( "vclick", function() {
5559 // Add hidden input if it doesn't already exist.
5560 if( $buttonPlaceholder === undefined ) {
5561 $buttonPlaceholder = $( "<input>", {
5563 name: $el.attr( "name" ),
5564 value: $el.attr( "value" )
5565 }).insertBefore( $el );
5567 // Bind to doc to remove after submit handling
5568 $( document ).one("submit", function(){
5569 $buttonPlaceholder.remove();
5571 // reset the local var so that the hidden input
5572 // will be re-added on subsequent clicks
5573 $buttonPlaceholder = undefined;
5581 $button.addClass( $.mobile.focusClass );
5585 $button.removeClass( $.mobile.focusClass );
5592 enable: function() {
5593 this.element.attr( "disabled", false );
5594 this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
5595 return this._setOption( "disabled", false );
5598 disable: function() {
5599 this.element.attr( "disabled", true );
5600 this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true );
5601 return this._setOption( "disabled", true );
5604 refresh: function() {
5605 var $el = this.element;
5607 if ( $el.prop("disabled") ) {
5613 // Grab the button's text element from its implementation-independent data item
5614 $( this.button.data( 'buttonElements' ).text ).text( $el.text() || $el.val() );
5618 //auto self-init widgets
5619 $( document ).bind( "pagecreate create", function( e ){
5620 $.mobile.button.prototype.enhanceWithin( e.target, true );
5625 (function( $, undefined ) {
5627 $.fn.controlgroup = function( options ) {
5628 function flipClasses( els, flCorners ) {
5629 els.removeClass( "ui-btn-corner-all ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-controlgroup-last ui-shadow" )
5630 .eq( 0 ).addClass( flCorners[ 0 ] )
5632 .last().addClass( flCorners[ 1 ] ).addClass( "ui-controlgroup-last" );
5635 return this.each(function() {
5636 var $el = $( this ),
5638 direction: $el.jqmData( "type" ) || "vertical",
5640 excludeInvisible: true,
5641 mini: $el.jqmData( "mini" )
5643 groupheading = $el.children( "legend" ),
5644 flCorners = o.direction == "horizontal" ? [ "ui-corner-left", "ui-corner-right" ] : [ "ui-corner-top", "ui-corner-bottom" ],
5645 type = $el.find( "input" ).first().attr( "type" );
5647 $el.wrapInner( "<div class='ui-controlgroup-controls'></div>" );
5649 // Replace legend with more stylable replacement div
5650 if ( groupheading.length ) {
5651 $( "<div role='heading' class='ui-controlgroup-label'>" + groupheading.html() + "</div>" ).insertBefore( $el.children(0) );
5652 groupheading.remove();
5655 $el.addClass( "ui-corner-all ui-controlgroup ui-controlgroup-" + o.direction );
5657 flipClasses( $el.find( ".ui-btn" + ( o.excludeInvisible ? ":visible" : "" ) ).not('.ui-slider-handle'), flCorners );
5658 flipClasses( $el.find( ".ui-btn-inner" ), flCorners );
5661 $el.addClass( "ui-shadow" );
5665 $el.addClass( "ui-mini" );
5671 // The pagecreate handler for controlgroup is in jquery.mobile.init because of the soft-dependency on the wrapped widgets
5675 (function( $, undefined ) {
5677 $( document ).bind( "pagecreate create", function( e ){
5679 //links within content areas, tests included with page
5683 .not( ".ui-btn, .ui-link-inherit, :jqmData(role='none'), :jqmData(role='nojs')" )
5684 .addClass( "ui-link" );
5692 var meta = $( "meta[name=viewport]" ),
5693 initialContent = meta.attr( "content" ),
5694 disabledZoom = initialContent + ",maximum-scale=1, user-scalable=no",
5695 enabledZoom = initialContent + ",maximum-scale=10, user-scalable=yes",
5696 disabledInitially = /(user-scalable[\s]*=[\s]*no)|(maximum-scale[\s]*=[\s]*1)[$,\s]/.test( initialContent );
5698 $.mobile.zoom = $.extend( {}, {
5699 enabled: !disabledInitially,
5701 disable: function( lock ) {
5702 if( !disabledInitially && !$.mobile.zoom.locked ){
5703 meta.attr( "content", disabledZoom );
5704 $.mobile.zoom.enabled = false;
5705 $.mobile.zoom.locked = lock || false;
5708 enable: function( unlock ) {
5709 if( !disabledInitially && ( !$.mobile.zoom.locked || unlock === true ) ){
5710 meta.attr( "content", enabledZoom );
5711 $.mobile.zoom.enabled = true;
5712 $.mobile.zoom.locked = false;
5715 restore: function() {
5716 if( !disabledInitially ){
5717 meta.attr( "content", initialContent );
5718 $.mobile.zoom.enabled = true;
5725 (function( $, undefined ) {
5727 $.widget( "mobile.textinput", $.mobile.widget, {
5730 // This option defaults to true on iOS devices.
5731 preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
5732 initSelector: "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea, input[type='time'], input[type='date'], input[type='month'], input[type='week'], input[type='datetime'], input[type='datetime-local'], input[type='color'], input:not([type])",
5733 clearSearchButtonText: "clear text"
5736 _create: function() {
5738 var input = this.element,
5740 theme = o.theme || $.mobile.getInheritedTheme( this.element, "c" ),
5741 themeclass = " ui-body-" + theme,
5742 mini = input.jqmData("mini") == true,
5743 miniclass = mini ? " ui-mini" : "",
5744 focusedEl, clearbtn;
5746 $( "label[for='" + input.attr( "id" ) + "']" ).addClass( "ui-input-text" );
5748 focusedEl = input.addClass("ui-input-text ui-body-"+ theme );
5750 // XXX: Temporary workaround for issue 785 (Apple bug 8910589).
5751 // Turn off autocorrect and autocomplete on non-iOS 5 devices
5752 // since the popup they use can't be dismissed by the user. Note
5753 // that we test for the presence of the feature by looking for
5754 // the autocorrect property on the input element. We currently
5755 // have no test for iOS 5 or newer so we're temporarily using
5756 // the touchOverflow support flag for jQM 1.0. Yes, I feel dirty. - jblas
5757 if ( typeof input[0].autocorrect !== "undefined" && !$.support.touchOverflow ) {
5758 // Set the attribute instead of the property just in case there
5759 // is code that attempts to make modifications via HTML.
5760 input[0].setAttribute( "autocorrect", "off" );
5761 input[0].setAttribute( "autocomplete", "off" );
5765 //"search" input widget
5766 if ( input.is( "[type='search'],:jqmData(type='search')" ) ) {
5768 focusedEl = input.wrap( "<div class='ui-input-search ui-shadow-inset ui-btn-corner-all ui-btn-shadow ui-icon-searchfield" + themeclass + miniclass + "'></div>" ).parent();
5769 clearbtn = $( "<a href='#' class='ui-input-clear' title='" + o.clearSearchButtonText + "'>" + o.clearSearchButtonText + "</a>" )
5770 .bind('click', function( event ) {
5774 .trigger( "change" );
5775 clearbtn.addClass( "ui-input-clear-hidden" );
5776 event.preventDefault();
5778 .appendTo( focusedEl )
5787 function toggleClear() {
5788 setTimeout(function() {
5789 clearbtn.toggleClass( "ui-input-clear-hidden", !input.val() );
5795 input.bind('paste cut keyup focus change blur', toggleClear);
5798 input.addClass( "ui-corner-all ui-shadow-inset" + themeclass + miniclass );
5801 input.focus(function() {
5802 focusedEl.addClass( $.mobile.focusClass );
5805 focusedEl.removeClass( $.mobile.focusClass );
5807 // In many situations, iOS will zoom into the select upon tap, this prevents that from happening
5808 .bind( "focus", function() {
5809 if( o.preventFocusZoom ){
5810 $.mobile.zoom.disable( true );
5813 .bind( "blur", function() {
5814 if( o.preventFocusZoom ){
5815 $.mobile.zoom.enable( true );
5820 if ( input.is( "textarea" ) ) {
5821 var extraLineHeight = 15,
5822 keyupTimeoutBuffer = 100,
5823 keyup = function() {
5824 var scrollHeight = input[ 0 ].scrollHeight,
5825 clientHeight = input[ 0 ].clientHeight;
5827 if ( clientHeight < scrollHeight ) {
5828 input.height(scrollHeight + extraLineHeight);
5833 input.keyup(function() {
5834 clearTimeout( keyupTimeout );
5835 keyupTimeout = setTimeout( keyup, keyupTimeoutBuffer );
5838 // binding to pagechange here ensures that for pages loaded via
5839 // ajax the height is recalculated without user input
5840 $( document ).one( "pagechange", keyup );
5842 // Issue 509: the browser is not providing scrollHeight properly until the styles load
5843 if ( $.trim( input.val() ) ) {
5844 // bind to the window load to make sure the height is calculated based on BOTH
5846 $( window ).load( keyup );
5851 disable: function(){
5852 ( this.element.attr( "disabled", true ).is( "[type='search'],:jqmData(type='search')" ) ?
5853 this.element.parent() : this.element ).addClass( "ui-disabled" );
5857 ( this.element.attr( "disabled", false).is( "[type='search'],:jqmData(type='search')" ) ?
5858 this.element.parent() : this.element ).removeClass( "ui-disabled" );
5862 //auto self-init widgets
5863 $( document ).bind( "pagecreate create", function( e ){
5864 $.mobile.textinput.prototype.enhanceWithin( e.target, true );
5869 (function( $, undefined ) {
5871 $.mobile.listview.prototype.options.filter = false;
5872 $.mobile.listview.prototype.options.filterPlaceholder = "Filter items...";
5873 $.mobile.listview.prototype.options.filterTheme = "c";
5874 $.mobile.listview.prototype.options.filterCallback = function( text, searchValue ){
5875 return text.toLowerCase().indexOf( searchValue ) === -1;
5878 $( document ).delegate( ":jqmData(role='listview')", "listviewcreate", function() {
5880 var list = $( this ),
5881 listview = list.data( "listview" );
5883 if ( !listview.options.filter ) {
5887 var wrapper = $( "<form>", {
5888 "class": "ui-listview-filter ui-bar-" + listview.options.filterTheme,
5891 search = $( "<input>", {
5892 placeholder: listview.options.filterPlaceholder
5894 .attr( "data-" + $.mobile.ns + "type", "search" )
5895 .jqmData( "lastval", "" )
5896 .bind( "keyup change", function() {
5898 var $this = $(this),
5899 val = this.value.toLowerCase(),
5901 lastval = $this.jqmData( "lastval" ) + "",
5906 // Change val as lastval for next execution
5907 $this.jqmData( "lastval" , val );
5908 if ( val.length < lastval.length || val.indexOf(lastval) !== 0 ) {
5910 // Removed chars or pasted something totally different, check all items
5911 listItems = list.children();
5914 // Only chars added, not removed, only use visible subset
5915 listItems = list.children( ":not(.ui-screen-hidden)" );
5920 // This handles hiding regular rows without the text we search for
5921 // and any list dividers without regular rows shown under it
5923 for ( var i = listItems.length - 1; i >= 0; i-- ) {
5924 item = $( listItems[ i ] );
5925 itemtext = item.jqmData( "filtertext" ) || item.text();
5927 if ( item.is( "li:jqmData(role=list-divider)" ) ) {
5929 item.toggleClass( "ui-filter-hidequeue" , !childItems );
5934 } else if ( listview.options.filterCallback( itemtext, val ) ) {
5937 item.toggleClass( "ui-filter-hidequeue" , true );
5940 // There's a shown item in the bucket
5945 // Show items, not marked to be hidden
5947 .filter( ":not(.ui-filter-hidequeue)" )
5948 .toggleClass( "ui-screen-hidden", false );
5950 // Hide items, marked to be hidden
5952 .filter( ".ui-filter-hidequeue" )
5953 .toggleClass( "ui-screen-hidden", true )
5954 .toggleClass( "ui-filter-hidequeue", false );
5958 //filtervalue is empty => show all
5959 listItems.toggleClass( "ui-screen-hidden", false );
5961 listview._refreshCorners();
5963 .appendTo( wrapper )
5966 if ( listview.options.inset ) {
5967 wrapper.addClass( "ui-listview-filter-inset" );
5970 wrapper.bind( "submit", function() {
5973 .insertBefore( list );
5978 ( function( $, undefined ) {
5980 $.widget( "mobile.slider", $.mobile.widget, {
5985 initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')",
5989 _create: function() {
5991 // TODO: Each of these should have comments explain what they're for
5994 control = this.element,
5996 parentTheme = $.mobile.getInheritedTheme( control, "c" ),
5998 theme = this.options.theme || parentTheme,
6000 trackTheme = this.options.trackTheme || parentTheme,
6002 cType = control[ 0 ].nodeName.toLowerCase(),
6004 selectClass = ( cType == "select" ) ? "ui-slider-switch" : "",
6006 controlID = control.attr( "id" ),
6008 $label = $( "[for='" + controlID + "']" ),
6010 labelID = $label.attr( "id" ) || controlID + "-label",
6012 label = $label.attr( "id", labelID ),
6015 return cType == "input" ? parseFloat( control.val() ) : control[0].selectedIndex;
6018 min = cType == "input" ? parseFloat( control.attr( "min" ) ) : 0,
6020 max = cType == "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1,
6022 step = window.parseFloat( control.attr( "step" ) || 1 ),
6024 inlineClass = ( this.options.inline || control.jqmData("inline") == true ) ? " ui-slider-inline" : "",
6026 miniClass = ( this.options.mini || control.jqmData("mini") ) ? " ui-slider-mini" : "",
6029 domHandle = document.createElement('a'),
6030 handle = $( domHandle ),
6031 domSlider = document.createElement('div'),
6032 slider = $( domSlider ),
6034 valuebg = control.jqmData("highlight") && cType != "select" ? (function() {
6035 var bg = document.createElement('div');
6036 bg.className = 'ui-slider-bg ' + $.mobile.activeBtnClass + ' ui-btn-corner-all';
6037 return $( bg ).prependTo( slider );
6042 domHandle.setAttribute( 'href', "#" );
6043 domSlider.setAttribute('role','application');
6044 domSlider.className = ['ui-slider ',selectClass," ui-btn-down-",trackTheme,' ui-btn-corner-all', inlineClass, miniClass].join("");
6045 domHandle.className = 'ui-slider-handle';
6046 domSlider.appendChild(domHandle);
6048 handle.buttonMarkup({ corners: true, theme: theme, shadow: true })
6051 "aria-valuemin": min,
6052 "aria-valuemax": max,
6053 "aria-valuenow": val(),
6054 "aria-valuetext": val(),
6056 "aria-labelledby": labelID
6065 userModified: false,
6069 if ( cType == "select" ) {
6070 var wrapper = document.createElement('div');
6071 wrapper.className = 'ui-slider-inneroffset';
6073 for(var j = 0,length = domSlider.childNodes.length;j < length;j++){
6074 wrapper.appendChild(domSlider.childNodes[j]);
6077 domSlider.appendChild(wrapper);
6079 // slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" );
6081 // make the handle move with a smooth transition
6082 handle.addClass( "ui-slider-handle-snapping" );
6084 options = control.find( "option" );
6086 for(var i = 0, optionsCount = options.length; i < optionsCount; i++){
6087 var side = !i ? "b":"a",
6088 sliderTheme = !i ? " ui-btn-down-" + trackTheme :( " " + $.mobile.activeBtnClass ),
6089 sliderLabel = document.createElement('div'),
6090 sliderImg = document.createElement('span');
6092 sliderImg.className = ['ui-slider-label ui-slider-label-',side,sliderTheme," ui-btn-corner-all"].join("");
6093 sliderImg.setAttribute('role','img');
6094 sliderImg.appendChild(document.createTextNode(options[i].innerHTML));
6095 $(sliderImg).prependTo( slider );
6098 self._labels = $( ".ui-slider-label", slider );
6102 label.addClass( "ui-slider" );
6104 // monitor the input for updated values
6105 control.addClass( cType === "input" ? "ui-slider-input" : "ui-slider-switch" )
6106 .change( function() {
6107 // if the user dragged the handle, the "change" event was triggered from inside refresh(); don't call refresh() again
6108 if (!self.mouseMoved) {
6109 self.refresh( val(), true );
6112 .keyup( function() { // necessary?
6113 self.refresh( val(), true, true );
6116 self.refresh( val(), true );
6119 // prevent screen drag when slider activated
6120 $( document ).bind( "vmousemove", function( event ) {
6121 if ( self.dragging ) {
6122 // self.mouseMoved must be updated before refresh() because it will be used in the control "change" event
6123 self.mouseMoved = true;
6125 if ( cType === "select" ) {
6126 // make the handle move in sync with the mouse
6127 handle.removeClass( "ui-slider-handle-snapping" );
6130 self.refresh( event );
6132 // only after refresh() you can calculate self.userModified
6133 self.userModified = self.beforeStart !== control[0].selectedIndex;
6138 slider.bind( "vmousedown", function( event ) {
6139 self.dragging = true;
6140 self.userModified = false;
6141 self.mouseMoved = false;
6143 if ( cType === "select" ) {
6144 self.beforeStart = control[0].selectedIndex;
6147 self.refresh( event );
6150 .bind( "vclick", false );
6152 slider.add( document )
6153 .bind( "vmouseup", function() {
6154 if ( self.dragging ) {
6156 self.dragging = false;
6158 if ( cType === "select") {
6160 // make the handle move with a smooth transition
6161 handle.addClass( "ui-slider-handle-snapping" );
6163 if ( self.mouseMoved ) {
6165 // this is a drag, change the value only if user dragged enough
6166 if ( self.userModified ) {
6167 self.refresh( self.beforeStart == 0 ? 1 : 0 );
6170 self.refresh( self.beforeStart );
6175 // this is just a click, change the value
6176 self.refresh( self.beforeStart == 0 ? 1 : 0 );
6181 self.mouseMoved = false;
6187 slider.insertAfter( control );
6189 // Only add focus class to toggle switch, sliders get it automatically from ui-btn
6190 if( cType == 'select' ) {
6193 slider.addClass( $.mobile.focusClass );
6197 slider.removeClass( $.mobile.focusClass );
6203 // NOTE force focus on handle
6204 vmousedown: function() {
6210 keydown: function( event ) {
6213 if ( self.options.disabled ) {
6217 // In all cases prevent the default and mark the handle as active
6218 switch ( event.keyCode ) {
6219 case $.mobile.keyCode.HOME:
6220 case $.mobile.keyCode.END:
6221 case $.mobile.keyCode.PAGE_UP:
6222 case $.mobile.keyCode.PAGE_DOWN:
6223 case $.mobile.keyCode.UP:
6224 case $.mobile.keyCode.RIGHT:
6225 case $.mobile.keyCode.DOWN:
6226 case $.mobile.keyCode.LEFT:
6227 event.preventDefault();
6229 if ( !self._keySliding ) {
6230 self._keySliding = true;
6231 $( this ).addClass( "ui-state-active" );
6236 // move the slider according to the keypress
6237 switch ( event.keyCode ) {
6238 case $.mobile.keyCode.HOME:
6239 self.refresh( min );
6241 case $.mobile.keyCode.END:
6242 self.refresh( max );
6244 case $.mobile.keyCode.PAGE_UP:
6245 case $.mobile.keyCode.UP:
6246 case $.mobile.keyCode.RIGHT:
6247 self.refresh( index + step );
6249 case $.mobile.keyCode.PAGE_DOWN:
6250 case $.mobile.keyCode.DOWN:
6251 case $.mobile.keyCode.LEFT:
6252 self.refresh( index - step );
6255 }, // remove active mark
6257 keyup: function( event ) {
6258 if ( self._keySliding ) {
6259 self._keySliding = false;
6260 $( this ).removeClass( "ui-state-active" );
6265 this.refresh(undefined, undefined, true);
6268 refresh: function( val, isfromControl, preventInputUpdate ) {
6270 if ( this.options.disabled || this.element.attr('disabled')) {
6274 var control = this.element, percent,
6275 cType = control[0].nodeName.toLowerCase(),
6276 min = cType === "input" ? parseFloat( control.attr( "min" ) ) : 0,
6277 max = cType === "input" ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length - 1,
6278 step = (cType === "input" && parseFloat( control.attr( "step" ) ) > 0) ? parseFloat(control.attr("step")) : 1;
6280 if ( typeof val === "object" ) {
6282 // a slight tolerance helped get to the ends of the slider
6284 if ( !this.dragging ||
6285 data.pageX < this.slider.offset().left - tol ||
6286 data.pageX > this.slider.offset().left + this.slider.width() + tol ) {
6289 percent = Math.round( ( ( data.pageX - this.slider.offset().left ) / this.slider.width() ) * 100 );
6291 if ( val == null ) {
6292 val = cType === "input" ? parseFloat( control.val() || 0 ) : control[0].selectedIndex;
6294 percent = ( parseFloat( val ) - min ) / ( max - min ) * 100;
6297 if ( isNaN( percent ) ) {
6301 if ( percent < 0 ) {
6305 if ( percent > 100 ) {
6309 var newval = ( percent / 100 ) * ( max - min ) + min;
6311 //from jQuery UI slider, the following source will round to the nearest step
6312 var valModStep = ( newval - min ) % step;
6313 var alignValue = newval - valModStep;
6315 if ( Math.abs( valModStep ) * 2 >= step ) {
6316 alignValue += ( valModStep > 0 ) ? step : ( -step );
6318 // Since JavaScript has problems with large floats, round
6319 // the final value to 5 digits after the decimal point (see jQueryUI: #4124)
6320 newval = parseFloat( alignValue.toFixed(5) );
6322 if ( newval < min ) {
6326 if ( newval > max ) {
6330 this.handle.css( "left", percent + "%" );
6332 "aria-valuenow": cType === "input" ? newval : control.find( "option" ).eq( newval ).attr( "value" ),
6333 "aria-valuetext": cType === "input" ? newval : control.find( "option" ).eq( newval ).getEncodedText(),
6334 title: cType === "input" ? newval : control.find( "option" ).eq( newval ).getEncodedText()
6336 this.valuebg && this.valuebg.css( "width", percent + "%" );
6338 // drag the label widths
6339 if ( this._labels ) {
6340 var handlePercent = this.handle.width() / this.slider.width() * 100,
6341 aPercent = percent && handlePercent + ( 100 - handlePercent ) * percent / 100,
6342 bPercent = percent === 100 ? 0 : Math.min( handlePercent + 100 - aPercent, 100 );
6344 this._labels.each(function(){
6345 var ab = $(this).is( ".ui-slider-label-a" );
6346 $( this ).width( ( ab ? aPercent : bPercent ) + "%" );
6350 if ( !preventInputUpdate ) {
6351 var valueChanged = false;
6353 // update control"s value
6354 if ( cType === "input" ) {
6355 valueChanged = control.val() !== newval;
6356 control.val( newval );
6358 valueChanged = control[ 0 ].selectedIndex !== newval;
6359 control[ 0 ].selectedIndex = newval;
6361 if ( !isfromControl && valueChanged ) {
6362 control.trigger( "change" );
6367 enable: function() {
6368 this.element.attr( "disabled", false );
6369 this.slider.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
6370 return this._setOption( "disabled", false );
6373 disable: function() {
6374 this.element.attr( "disabled", true );
6375 this.slider.addClass( "ui-disabled" ).attr( "aria-disabled", true );
6376 return this._setOption( "disabled", true );
6381 //auto self-init widgets
6382 $( document ).bind( "pagecreate create", function( e ){
6383 $.mobile.slider.prototype.enhanceWithin( e.target, true );
6388 (function( $, undefined ) {
6390 $.widget( "mobile.selectmenu", $.mobile.widget, {
6401 hidePlaceholderMenuItems: true,
6404 // This option defaults to true on iOS devices.
6405 preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
6406 initSelector: "select:not(:jqmData(role='slider'))",
6410 _button: function(){
6411 return $( "<div/>" );
6414 _setDisabled: function( value ) {
6415 this.element.attr( "disabled", value );
6416 this.button.attr( "aria-disabled", value );
6417 return this._setOption( "disabled", value );
6420 _focusButton : function() {
6423 setTimeout( function() {
6424 self.button.focus();
6428 _selectOptions: function() {
6429 return this.select.find( "option" );
6432 // setup items that are generally necessary for select menu extension
6433 _preExtension: function(){
6435 // TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
6436 /* if( $el[0].className.length ) {
6437 classes = $el[0].className;
6439 if( !!~this.element[0].className.indexOf( "ui-btn-left" ) ) {
6440 classes = " ui-btn-left";
6443 if( !!~this.element[0].className.indexOf( "ui-btn-right" ) ) {
6444 classes = " ui-btn-right";
6447 this.select = this.element.wrap( "<div class='ui-select" + classes + "'>" );
6448 this.selectID = this.select.attr( "id" );
6449 this.label = $( "label[for='"+ this.selectID +"']" ).addClass( "ui-select" );
6450 this.isMultiple = this.select[ 0 ].multiple;
6451 if ( !this.options.theme ) {
6452 this.options.theme = $.mobile.getInheritedTheme( this.select, "c" );
6456 _create: function() {
6457 this._preExtension();
6459 // Allows for extension of the native select for custom selects and other plugins
6460 // see select.custom for example extension
6461 // TODO explore plugin registration
6462 this._trigger( "beforeCreate" );
6464 this.button = this._button();
6468 options = this.options,
6470 inline = options.inline || this.select.jqmData( "inline" ),
6471 mini = options.mini || this.select.jqmData( "mini" ),
6472 iconpos = options.icon ? ( options.iconpos || this.select.jqmData( "iconpos" ) ) : false,
6474 // IE throws an exception at options.item() function when
6475 // there is no selected item
6476 // select first in this case
6477 selectedIndex = this.select[ 0 ].selectedIndex == -1 ? 0 : this.select[ 0 ].selectedIndex,
6479 // TODO values buttonId and menuId are undefined here
6480 button = this.button
6481 .text( $( this.select[ 0 ].options.item( selectedIndex ) ).text() )
6482 .insertBefore( this.select )
6484 theme: options.theme,
6488 corners: options.corners,
6489 shadow: options.shadow,
6490 iconshadow: options.iconshadow,
6494 // Opera does not properly support opacity on select elements
6495 // In Mini, it hides the element, but not its text
6496 // On the desktop,it seems to do the opposite
6497 // for these reasons, using the nativeMenu option results in a full native select in Opera
6498 if ( options.nativeMenu && window.opera && window.opera.version ) {
6499 button.addClass( "ui-select-nativeonly" );
6502 // Add counter for multi selects
6503 if ( this.isMultiple ) {
6504 this.buttonCount = $( "<span>" )
6505 .addClass( "ui-li-count ui-btn-up-c ui-btn-corner-all" )
6507 .appendTo( button.addClass('ui-li-has-count') );
6510 // Disable if specified
6511 if ( options.disabled || this.element.attr('disabled')) {
6515 // Events on native select
6516 this.select.change( function() {
6527 .appendTo( self.button )
6528 .bind( "vmousedown", function() {
6529 // Add active class to button
6530 self.button.addClass( $.mobile.activeBtnClass );
6532 .bind( "focus", function() {
6533 self.button.addClass( $.mobile.focusClass );
6535 .bind( "blur", function() {
6536 self.button.removeClass( $.mobile.focusClass );
6538 .bind( "focus vmouseover", function() {
6539 self.button.trigger( "vmouseover" );
6541 .bind( "vmousemove", function() {
6542 // Remove active class on scroll/touchmove
6543 self.button.removeClass( $.mobile.activeBtnClass );
6545 .bind( "change blur vmouseout", function() {
6546 self.button.trigger( "vmouseout" )
6547 .removeClass( $.mobile.activeBtnClass );
6549 .bind( "change blur", function() {
6550 self.button.removeClass( "ui-btn-down-" + self.options.theme );
6553 // In many situations, iOS will zoom into the select upon tap, this prevents that from happening
6554 self.button.bind( "vmousedown", function() {
6555 if( self.options.preventFocusZoom ){
6556 $.mobile.zoom.disable( true );
6559 .bind( "mouseup", function() {
6560 if( self.options.preventFocusZoom ){
6561 $.mobile.zoom.enable( true );
6566 selected: function() {
6567 return this._selectOptions().filter( ":selected" );
6570 selectedIndices: function() {
6573 return this.selected().map( function() {
6574 return self._selectOptions().index( this );
6578 setButtonText: function() {
6579 var self = this, selected = this.selected();
6581 this.button.find( ".ui-btn-text" ).text( function() {
6582 if ( !self.isMultiple ) {
6583 return selected.text();
6586 return selected.length ? selected.map( function() {
6587 return $( this ).text();
6588 }).get().join( ", " ) : self.placeholder;
6592 setButtonCount: function() {
6593 var selected = this.selected();
6595 // multiple count inside button
6596 if ( this.isMultiple ) {
6597 this.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length );
6601 refresh: function() {
6602 this.setButtonText();
6603 this.setButtonCount();
6606 // open and close preserved in native selects
6607 // to simplify users code when looping over selects
6611 disable: function() {
6612 this._setDisabled( true );
6613 this.button.addClass( "ui-disabled" );
6616 enable: function() {
6617 this._setDisabled( false );
6618 this.button.removeClass( "ui-disabled" );
6622 //auto self-init widgets
6623 $( document ).bind( "pagecreate create", function( e ){
6624 $.mobile.selectmenu.prototype.enhanceWithin( e.target, true );
6629 * custom "selectmenu" plugin
6632 (function( $, undefined ) {
6633 var extendSelect = function( widget ){
6635 var select = widget.select,
6636 selectID = widget.selectID,
6637 label = widget.label,
6638 thisPage = widget.select.closest( ".ui-page" ),
6639 screen = $( "<div>", {"class": "ui-selectmenu-screen ui-screen-hidden"} ).appendTo( thisPage ),
6640 selectOptions = widget._selectOptions(),
6641 isMultiple = widget.isMultiple = widget.select[ 0 ].multiple,
6642 buttonId = selectID + "-button",
6643 menuId = selectID + "-menu",
6644 menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' data-" +$.mobile.ns + "theme='"+ widget.options.theme +"' data-" +$.mobile.ns + "overlay-theme='"+ widget.options.overlayTheme +"'>" +
6645 "<div data-" + $.mobile.ns + "role='header'>" +
6646 "<div class='ui-title'>" + label.getEncodedText() + "</div>"+
6648 "<div data-" + $.mobile.ns + "role='content'></div>"+
6651 listbox = $("<div>", { "class": "ui-selectmenu ui-selectmenu-hidden ui-overlay-shadow ui-corner-all ui-body-" + widget.options.overlayTheme + " " + $.mobile.defaultDialogTransition } ).insertAfter(screen),
6654 "class": "ui-selectmenu-list",
6657 "aria-labelledby": buttonId
6658 }).attr( "data-" + $.mobile.ns + "theme", widget.options.theme ).appendTo( listbox ),
6660 header = $( "<div>", {
6661 "class": "ui-header ui-bar-" + widget.options.theme
6662 }).prependTo( listbox ),
6664 headerTitle = $( "<h1>", {
6666 }).appendTo( header ),
6672 if( widget.isMultiple ) {
6673 headerClose = $( "<a>", {
6674 "text": widget.options.closeText,
6676 "class": "ui-btn-left"
6677 }).attr( "data-" + $.mobile.ns + "iconpos", "notext" ).attr( "data-" + $.mobile.ns + "icon", "delete" ).appendTo( header ).buttonMarkup();
6681 select: widget.select,
6689 selectOptions: selectOptions,
6690 isMultiple: isMultiple,
6691 theme: widget.options.theme,
6695 headerTitle: headerTitle,
6696 headerClose: headerClose,
6697 menuPageContent: menuPageContent,
6698 menuPageClose: menuPageClose,
6704 // Create list from select, update state
6707 self.select.attr( "tabindex", "-1" ).focus(function() {
6709 self.button.focus();
6713 self.button.bind( "vclick keydown" , function( event ) {
6714 if ( event.type == "vclick" ||
6715 event.keyCode && ( event.keyCode === $.mobile.keyCode.ENTER ||
6716 event.keyCode === $.mobile.keyCode.SPACE ) ) {
6719 event.preventDefault();
6723 // Events for list items
6724 self.list.attr( "role", "listbox" )
6725 .bind( "focusin", function( e ){
6727 .attr( "tabindex", "0" )
6728 .trigger( "vmouseover" );
6731 .bind( "focusout", function( e ){
6733 .attr( "tabindex", "-1" )
6734 .trigger( "vmouseout" );
6736 .delegate( "li:not(.ui-disabled, .ui-li-divider)", "click", function( event ) {
6738 // index of option tag to be selected
6739 var oldIndex = self.select[ 0 ].selectedIndex,
6740 newIndex = self.list.find( "li:not(.ui-li-divider)" ).index( this ),
6741 option = self._selectOptions().eq( newIndex )[ 0 ];
6743 // toggle selected status on the tag for multi selects
6744 option.selected = self.isMultiple ? !option.selected : true;
6746 // toggle checkbox class for multiple selects
6747 if ( self.isMultiple ) {
6748 $( this ).find( ".ui-icon" )
6749 .toggleClass( "ui-icon-checkbox-on", option.selected )
6750 .toggleClass( "ui-icon-checkbox-off", !option.selected );
6753 // trigger change if value changed
6754 if ( self.isMultiple || oldIndex !== newIndex ) {
6755 self.select.trigger( "change" );
6758 // hide custom select for single selects only - otherwise focus clicked item
6759 // We need to grab the clicked item the hard way, because the list may have been rebuilt
6760 if ( self.isMultiple ) {
6761 self.list.find( "li:not(.ui-li-divider)" ).eq( newIndex )
6762 .addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
6768 event.preventDefault();
6770 .keydown(function( event ) { //keyboard events for menu items
6771 var target = $( event.target ),
6772 li = target.closest( "li" ),
6775 // switch logic based on which key was pressed
6776 switch ( event.keyCode ) {
6777 // up or left arrow keys
6779 prev = li.prev().not( ".ui-selectmenu-placeholder" );
6781 if( prev.is( ".ui-li-divider" ) ) {
6785 // if there's a previous option, focus it
6786 if ( prev.length ) {
6789 .attr( "tabindex", "-1" );
6791 prev.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
6797 // down or right arrow keys
6801 if( next.is( ".ui-li-divider" ) ) {
6805 // if there's a next option, focus it
6806 if ( next.length ) {
6809 .attr( "tabindex", "-1" );
6811 next.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
6817 // If enter or space is pressed, trigger click
6820 target.trigger( "click" );
6827 // button refocus ensures proper height calculation
6828 // by removing the inline style and ensuring page inclusion
6829 self.menuPage.bind( "pagehide", function() {
6830 self.list.appendTo( self.listbox );
6831 self._focusButton();
6833 // TODO centralize page removal binding / handling in the page plugin.
6834 // Suggestion from @jblas to do refcounting
6836 // TODO extremely confusing dependency on the open method where the pagehide.remove
6837 // bindings are stripped to prevent the parent page from disappearing. The way
6838 // we're keeping pages in the DOM right now sucks
6840 // rebind the page remove that was unbound in the open function
6841 // to allow for the parent page removal from actions other than the use
6842 // of a dialog sized custom select
6844 // doing this here provides for the back button on the custom select dialog
6845 $.mobile._bindPageRemove.call( self.thisPage );
6848 // Events on "screen" overlay
6849 self.screen.bind( "vclick", function( event ) {
6853 // Close button on small overlays
6854 if( self.isMultiple ){
6855 self.headerClose.click( function() {
6856 if ( self.menuType == "overlay" ) {
6863 // track this dependency so that when the parent page
6864 // is removed on pagehide it will also remove the menupage
6865 self.thisPage.addDependents( this.menuPage );
6868 _isRebuildRequired: function() {
6869 var list = this.list.find( "li" ),
6870 options = this._selectOptions();
6872 // TODO exceedingly naive method to determine difference
6873 // ignores value changes etc in favor of a forcedRebuild
6874 // from the user in the refresh method
6875 return options.text() !== list.text();
6878 selected: function() {
6879 return this._selectOptions().filter( ":selected:not(:jqmData(placeholder='true'))" );
6882 refresh: function( forceRebuild , foo ){
6884 select = this.element,
6885 isMultiple = this.isMultiple,
6888 if ( forceRebuild || this._isRebuildRequired() ) {
6892 indicies = this.selectedIndices();
6894 self.setButtonText();
6895 self.setButtonCount();
6897 self.list.find( "li:not(.ui-li-divider)" )
6898 .removeClass( $.mobile.activeBtnClass )
6899 .attr( "aria-selected", false )
6900 .each(function( i ) {
6902 if ( $.inArray( i, indicies ) > -1 ) {
6903 var item = $( this );
6905 // Aria selected attr
6906 item.attr( "aria-selected", true );
6908 // Multiple selects: add the "on" checkbox state to the icon
6909 if ( self.isMultiple ) {
6910 item.find( ".ui-icon" ).removeClass( "ui-icon-checkbox-off" ).addClass( "ui-icon-checkbox-on" );
6912 if( item.is( ".ui-selectmenu-placeholder" ) ) {
6913 item.next().addClass( $.mobile.activeBtnClass );
6915 item.addClass( $.mobile.activeBtnClass );
6923 if ( this.options.disabled || !this.isOpen ) {
6929 if ( self.menuType == "page" ) {
6930 // doesn't solve the possible issue with calling change page
6931 // where the objects don't define data urls which prevents dialog key
6932 // stripping - changePage has incoming refactor
6933 window.history.back();
6935 self.screen.addClass( "ui-screen-hidden" );
6936 self.listbox.addClass( "ui-selectmenu-hidden" ).removeAttr( "style" ).removeClass( "in" );
6937 self.list.appendTo( self.listbox );
6938 self._focusButton();
6941 // allow the dialog to be closed again
6942 self.isOpen = false;
6946 if ( this.options.disabled ) {
6951 $window = $( window ),
6952 selfListParent = self.list.parent(),
6953 menuHeight = selfListParent.outerHeight(),
6954 menuWidth = selfListParent.outerWidth(),
6955 activePage = $( ".ui-page-active" ),
6956 tScrollElem = activePage,
6957 scrollTop = $window.scrollTop(),
6958 btnOffset = self.button.offset().top,
6959 screenHeight = $window.height(),
6960 screenWidth = $window.width();
6962 //add active class to button
6963 self.button.addClass( $.mobile.activeBtnClass );
6965 //remove after delay
6966 setTimeout( function() {
6967 self.button.removeClass( $.mobile.activeBtnClass );
6970 function focusMenuItem() {
6971 var selector = self.list.find( "." + $.mobile.activeBtnClass + " a" );
6972 if ( selector.length === 0 ) {
6973 selector = self.list.find( "li.ui-btn:not(:jqmData(placeholder='true')) a" );
6975 selector.first().focus().closest( "li" ).addClass( "ui-btn-down-" + widget.options.theme );
6978 if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) {
6980 self.menuPage.appendTo( $.mobile.pageContainer ).page();
6981 self.menuPageContent = menuPage.find( ".ui-content" );
6982 self.menuPageClose = menuPage.find( ".ui-header a" );
6984 // prevent the parent page from being removed from the DOM,
6985 // otherwise the results of selecting a list item in the dialog
6986 // fall into a black hole
6987 self.thisPage.unbind( "pagehide.remove" );
6989 //for WebOS/Opera Mini (set lastscroll using button offset)
6990 if ( scrollTop == 0 && btnOffset > screenHeight ) {
6991 self.thisPage.one( "pagehide", function() {
6992 $( this ).jqmData( "lastScroll", btnOffset );
6996 self.menuPage.one( "pageshow", function() {
7001 self.menuType = "page";
7002 self.menuPageContent.append( self.list );
7003 self.menuPage.find("div .ui-title").text(self.label.text());
7004 $.mobile.changePage( self.menuPage, {
7005 transition: $.mobile.defaultDialogTransition
7008 self.menuType = "overlay";
7010 self.screen.height( $(document).height() )
7011 .removeClass( "ui-screen-hidden" );
7013 // Try and center the overlay over the button
7014 var roomtop = btnOffset - scrollTop,
7015 roombot = scrollTop + screenHeight - btnOffset,
7016 halfheight = menuHeight / 2,
7017 maxwidth = parseFloat( self.list.parent().css( "max-width" ) ),
7020 if ( roomtop > menuHeight / 2 && roombot > menuHeight / 2 ) {
7021 newtop = btnOffset + ( self.button.outerHeight() / 2 ) - halfheight;
7023 // 30px tolerance off the edges
7024 newtop = roomtop > roombot ? scrollTop + screenHeight - menuHeight - 30 : scrollTop + 30;
7027 // If the menuwidth is smaller than the screen center is
7028 if ( menuWidth < maxwidth ) {
7029 newleft = ( screenWidth - menuWidth ) / 2;
7032 //otherwise insure a >= 30px offset from the left
7033 newleft = self.button.offset().left + self.button.outerWidth() / 2 - menuWidth / 2;
7035 // 30px tolerance off the edges
7036 if ( newleft < 30 ) {
7038 } else if ( (newleft + menuWidth) > screenWidth ) {
7039 newleft = screenWidth - menuWidth - 30;
7043 self.listbox.append( self.list )
7044 .removeClass( "ui-selectmenu-hidden" )
7053 // duplicate with value set in page show for dialog sized selects
7058 _buildList: function() {
7061 placeholder = this.placeholder,
7062 needPlaceholder = true,
7065 dataIcon = self.isMultiple ? "checkbox-off" : "false";
7067 self.list.empty().filter( ".ui-listview" ).listview( "destroy" );
7069 var $options = self.select.find("option"),
7070 numOptions = $options.length,
7071 select = this.select[ 0 ],
7072 dataPrefix = 'data-' + $.mobile.ns,
7073 dataIndexAttr = dataPrefix + 'option-index',
7074 dataIconAttr = dataPrefix + 'icon',
7075 dataRoleAttr = dataPrefix + 'role',
7076 dataPlaceholderAttr = dataPrefix + 'placeholder',
7077 fragment = document.createDocumentFragment(),
7078 isPlaceholderItem = false,
7081 for (var i = 0; i < numOptions;i++, isPlaceholderItem = false){
7082 var option = $options[i],
7083 $option = $(option),
7084 parent = option.parentNode,
7085 text = $option.text(),
7086 anchor = document.createElement('a'),
7089 anchor.setAttribute('href','#');
7090 anchor.appendChild(document.createTextNode(text));
7092 // Are we inside an optgroup?
7093 if (parent !== select && parent.nodeName.toLowerCase() === "optgroup"){
7094 var optLabel = parent.getAttribute('label');
7095 if ( optLabel != optGroup) {
7096 var divider = document.createElement('li');
7097 divider.setAttribute(dataRoleAttr,'list-divider');
7098 divider.setAttribute('role','option');
7099 divider.setAttribute('tabindex','-1');
7100 divider.appendChild(document.createTextNode(optLabel));
7101 fragment.appendChild(divider);
7102 optGroup = optLabel;
7106 if (needPlaceholder && (!option.getAttribute( "value" ) || text.length == 0 || $option.jqmData( "placeholder" ))) {
7107 needPlaceholder = false;
7108 isPlaceholderItem = true;
7110 // If we have identified a placeholder, mark it retroactively in the select as well
7111 option.setAttribute( dataPlaceholderAttr, true );
7112 if ( o.hidePlaceholderMenuItems ) {
7113 classes.push( "ui-selectmenu-placeholder" );
7116 placeholder = self.placeholder = text;
7120 var item = document.createElement('li');
7121 if ( option.disabled ) {
7122 classes.push( "ui-disabled" );
7123 item.setAttribute('aria-disabled',true);
7125 item.setAttribute(dataIndexAttr,i);
7126 item.setAttribute(dataIconAttr,dataIcon);
7127 if ( isPlaceholderItem ) {
7128 item.setAttribute( dataPlaceholderAttr, true );
7130 item.className = classes.join(" ");
7131 item.setAttribute('role','option');
7132 anchor.setAttribute('tabindex','-1');
7133 item.appendChild(anchor);
7134 fragment.appendChild(item);
7137 self.list[0].appendChild(fragment);
7139 // Hide header if it's not a multiselect and there's no placeholder
7140 if ( !this.isMultiple && !placeholder.length ) {
7143 this.headerTitle.text( this.placeholder );
7146 // Now populated, create listview
7147 self.list.listview();
7150 _button: function(){
7154 // TODO value is undefined at creation
7155 "id": this.buttonId,
7156 "aria-haspopup": "true",
7158 // TODO value is undefined at creation
7159 "aria-owns": this.menuId
7165 // issue #3894 - core doesn't triggered events on disabled delegates
7166 $( document ).bind( "selectmenubeforecreate", function( event ){
7167 var selectmenuWidget = $( event.target ).data( "selectmenu" );
7169 if( !selectmenuWidget.options.nativeMenu ){
7170 extendSelect( selectmenuWidget );
7175 (function( $, undefined ) {
7178 $.widget( "mobile.fixedtoolbar", $.mobile.widget, {
7180 visibleOnPageShow: true,
7181 disablePageZoom: true,
7182 transition: "slide", //can be none, fade, slide (slide maps to slideup or slidedown)
7185 tapToggleBlacklist: "a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed",
7186 hideDuringFocus: "input, textarea, select",
7187 updatePagePadding: true,
7188 trackPersistentToolbars: true,
7190 // Browser detection! Weeee, here we go...
7191 // Unfortunately, position:fixed is costly, not to mention probably impossible, to feature-detect accurately.
7192 // Some tests exist, but they currently return false results in critical devices and browsers, which could lead to a broken experience.
7193 // Testing fixed positioning is also pretty obtrusive to page load, requiring injected elements and scrolling the window
7194 // The following function serves to rule out some popular browsers with known fixed-positioning issues
7195 // This is a plugin option like any other, so feel free to improve or overwrite it
7196 supportBlacklist: function(){
7198 ua = navigator.userAgent,
7199 platform = navigator.platform,
7200 // Rendering engine is Webkit, and capture major version
7201 wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ),
7202 wkversion = !!wkmatch && wkmatch[ 1 ],
7203 ffmatch = ua.match( /Fennec\/([0-9]+)/ ),
7204 ffversion = !!ffmatch && ffmatch[ 1 ],
7205 operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ ),
7206 omversion = !!operammobilematch && operammobilematch[ 1 ];
7209 // iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5)
7210 ( ( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534 )
7213 ( w.operamini && ({}).toString.call( w.operamini ) === "[object OperaMini]" )
7215 ( operammobilematch && omversion < 7458 )
7217 //Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2)
7218 ( ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533 )
7220 // Firefox Mobile before 6.0 -
7221 ( ffversion && ffversion < 6 )
7223 // WebOS less than 3
7224 ( "palmGetResource" in window && wkversion && wkversion < 534 )
7227 ( ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1 )
7234 initSelector: ":jqmData(position='fixed')"
7237 _create: function() {
7242 tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer",
7243 $page = $el.closest(".ui-page");
7245 // Feature detecting support for
7246 if( o.supportBlacklist() ){
7251 $el.addClass( "ui-"+ tbtype +"-fixed" );
7253 // "fullscreen" overlay positioning
7255 $el.addClass( "ui-"+ tbtype +"-fullscreen" );
7256 $page.addClass( "ui-page-" + tbtype + "-fullscreen" );
7258 // If not fullscreen, add class to page to set top or bottom padding
7260 $page.addClass( "ui-page-" + tbtype + "-fixed" );
7263 self._addTransitionClass();
7264 self._bindPageEvents();
7265 self._bindToggleHandlers();
7268 _addTransitionClass: function(){
7269 var tclass = this.options.transition;
7271 if( tclass && tclass !== "none" ){
7272 // use appropriate slide for header or footer
7273 if( tclass === "slide" ){
7274 tclass = this.element.is( ".ui-header" ) ? "slidedown" : "slideup";
7277 this.element.addClass( tclass );
7281 _bindPageEvents: function(){
7286 //page event bindings
7287 // Fixed toolbars require page zoom to be disabled, otherwise usability issues crop up
7288 // This method is meant to disable zoom while a fixed-positioned toolbar page is visible
7289 $el.closest( ".ui-page" )
7290 .bind( "pagebeforeshow", function(){
7291 if( o.disablePageZoom ){
7292 $.mobile.zoom.disable( true );
7294 if( !o.visibleOnPageShow ){
7298 .bind( "webkitAnimationStart animationstart updatelayout", function(){
7299 var thisPage = this;
7300 if( o.updatePagePadding ){
7301 self.updatePagePadding( thisPage );
7304 .bind( "pageshow", function(){
7305 var thisPage = this;
7306 self.updatePagePadding( thisPage );
7307 if( o.updatePagePadding ){
7308 $( window ).bind( "throttledresize." + self.widgetName, function(){
7309 self.updatePagePadding( thisPage );
7313 .bind( "pagebeforehide", function( e, ui ){
7314 if( o.disablePageZoom ){
7315 $.mobile.zoom.enable( true );
7317 if( o.updatePagePadding ){
7318 $( window ).unbind( "throttledresize." + self.widgetName );
7321 if( o.trackPersistentToolbars ){
7322 var thisFooter = $( ".ui-footer-fixed:jqmData(id)", this ),
7323 thisHeader = $( ".ui-header-fixed:jqmData(id)", this ),
7324 nextFooter = thisFooter.length && ui.nextPage && $( ".ui-footer-fixed:jqmData(id='" + thisFooter.jqmData( "id" ) + "')", ui.nextPage ),
7325 nextHeader = thisHeader.length && ui.nextPage && $( ".ui-header-fixed:jqmData(id='" + thisHeader.jqmData( "id" ) + "')", ui.nextPage );
7327 nextFooter = nextFooter || $();
7329 if( nextFooter.length || nextHeader.length ){
7331 nextFooter.add( nextHeader ).appendTo( $.mobile.pageContainer );
7333 ui.nextPage.one( "pageshow", function(){
7334 nextFooter.add( nextHeader ).appendTo( this );
7343 // This will set the content element's top or bottom padding equal to the toolbar's height
7344 updatePagePadding: function( tbPage ) {
7345 var $el = this.element,
7346 header = $el.is( ".ui-header" );
7348 // This behavior only applies to "fixed", not "fullscreen"
7349 if( this.options.fullscreen ){ return; }
7351 tbPage = tbPage || $el.closest( ".ui-page" );
7352 $( tbPage ).css( "padding-" + ( header ? "top" : "bottom" ), $el.outerHeight() );
7355 _useTransition: function( notransition ){
7356 var $win = $( window ),
7358 scroll = $win.scrollTop(),
7359 elHeight = $el.height(),
7360 pHeight = $el.closest( ".ui-page" ).height(),
7361 viewportHeight = $.mobile.getScreenHeight(),
7362 tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer";
7364 return !notransition &&
7365 ( this.options.transition && this.options.transition !== "none" &&
7367 ( tbtype === "header" && !this.options.fullscreen && scroll > elHeight ) ||
7368 ( tbtype === "footer" && !this.options.fullscreen && scroll + viewportHeight < pHeight - elHeight )
7369 ) || this.options.fullscreen
7373 show: function( notransition ){
7374 var hideClass = "ui-fixed-hidden",
7377 if( this._useTransition( notransition ) ){
7379 .removeClass( "out " + hideClass )
7383 $el.removeClass( hideClass );
7385 this._visible = true;
7388 hide: function( notransition ){
7389 var hideClass = "ui-fixed-hidden",
7391 // if it's a slide transition, our new transitions need the reverse class as well to slide outward
7392 outclass = "out" + ( this.options.transition === "slide" ? " reverse" : "" );
7394 if( this._useTransition( notransition ) ){
7396 .addClass( outclass )
7397 .removeClass( "in" )
7398 .animationComplete( function(){
7399 $el.addClass( hideClass ).removeClass( outclass );
7403 $el.addClass( hideClass ).removeClass( outclass );
7405 this._visible = false;
7409 this[ this._visible ? "hide" : "show" ]();
7412 _bindToggleHandlers: function(){
7418 $el.closest( ".ui-page" )
7419 .bind( "vclick", function( e ){
7420 if( o.tapToggle && !$( e.target ).closest( o.tapToggleBlacklist ).length ){
7424 .bind( "focusin focusout", function( e ){
7425 if( screen.width < 500 && $( e.target ).is( o.hideDuringFocus ) && !$( e.target ).closest( ".ui-header-fixed, .ui-footer-fixed" ).length ){
7426 self[ ( e.type === "focusin" && self._visible ) ? "hide" : "show" ]();
7431 destroy: function(){
7432 this.element.removeClass( "ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden" );
7433 this.element.closest( ".ui-page" ).removeClass( "ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen" );
7438 //auto self-init widgets
7440 .bind( "pagecreate create", function( e ){
7442 // DEPRECATED in 1.1: support for data-fullscreen=true|false on the page element.
7443 // This line ensures it still works, but we recommend moving the attribute to the toolbars themselves.
7444 if( $( e.target ).jqmData( "fullscreen" ) ){
7445 $( $.mobile.fixedtoolbar.prototype.options.initSelector, e.target ).not( ":jqmData(fullscreen)" ).jqmData( "fullscreen", true );
7448 $.mobile.fixedtoolbar.prototype.enhanceWithin( e.target );
7453 ( function( $, window ) {
7455 // This fix addresses an iOS bug, so return early if the UA claims it's something else.
7456 if( !(/iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1 ) ){
7460 var zoom = $.mobile.zoom,
7463 function checkTilt( e ){
7464 evt = e.originalEvent;
7465 aig = evt.accelerationIncludingGravity;
7467 x = Math.abs( aig.x );
7468 y = Math.abs( aig.y );
7469 z = Math.abs( aig.z );
7471 // If portrait orientation and in one of the danger zones
7472 if( !window.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ){
7477 else if( !zoom.enabled ){
7483 .bind( "orientationchange.iosorientationfix", zoom.enable )
7484 .bind( "devicemotion.iosorientationfix", checkTilt );
7488 ( function( $, window, undefined ) {
7489 var $html = $( "html" ),
7490 $head = $( "head" ),
7491 $window = $( window );
7493 // trigger mobileinit event - useful hook for configuring $.mobile settings before they're used
7494 $( window.document ).trigger( "mobileinit" );
7496 // support conditions
7497 // if device support condition(s) aren't met, leave things as they are -> a basic, usable experience,
7498 // otherwise, proceed with the enhancements
7499 if ( !$.mobile.gradeA() ) {
7503 // override ajaxEnabled on platforms that have known conflicts with hash history updates
7504 // or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini)
7505 if ( $.mobile.ajaxBlacklist ) {
7506 $.mobile.ajaxEnabled = false;
7509 // Add mobile, initial load "rendering" classes to docEl
7510 $html.addClass( "ui-mobile ui-mobile-rendering" );
7512 // This is a fallback. If anything goes wrong (JS errors, etc), or events don't fire,
7513 // this ensures the rendering class is removed after 5 seconds, so content is visible and accessible
7514 setTimeout( hideRenderingClass, 5000 );
7516 // loading div which appears during Ajax requests
7517 // will not appear if $.mobile.loadingMessage is false
7518 var loaderClass = "ui-loader",
7519 $loader = $( "<div class='" + loaderClass + "'><span class='ui-icon ui-icon-loading'></span><h1></h1></div>" );
7521 // For non-fixed supportin browsers. Position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top
7522 function fakeFixLoader(){
7523 var activeBtn = $( "." + $.mobile.activeBtnClass ).first();
7527 top: $.support.scrollTop && $window.scrollTop() + $window.height() / 2 ||
7528 activeBtn.length && activeBtn.offset().top || 100
7532 // check position of loader to see if it appears to be "fixed" to center
7533 // if not, use abs positioning
7534 function checkLoaderPosition(){
7535 var offset = $loader.offset(),
7536 scrollTop = $window.scrollTop(),
7537 screenHeight = $.mobile.getScreenHeight();
7539 if( offset.top < scrollTop || (offset.top - scrollTop) > screenHeight ) {
7540 $loader.addClass( "ui-loader-fakefix" );
7543 .unbind( "scroll", checkLoaderPosition )
7544 .bind( "scroll", fakeFixLoader );
7548 //remove initial build class (only present on first pageshow)
7549 function hideRenderingClass(){
7550 $html.removeClass( "ui-mobile-rendering" );
7553 $.extend($.mobile, {
7554 // turn on/off page loading message.
7555 showPageLoadingMsg: function( theme, msgText, textonly ) {
7556 $html.addClass( "ui-loading" );
7558 if ( $.mobile.loadingMessage ) {
7559 // text visibility from argument takes priority
7560 var textVisible = textonly || $.mobile.loadingMessageTextVisible;
7562 theme = theme || $.mobile.loadingMessageTheme,
7565 .attr( "class", loaderClass + " ui-corner-all ui-body-" + ( theme || "a" ) + " ui-loader-" + ( textVisible ? "verbose" : "default" ) + ( textonly ? " ui-loader-textonly" : "" ) )
7567 .text( msgText || $.mobile.loadingMessage )
7569 .appendTo( $.mobile.pageContainer );
7571 checkLoaderPosition();
7572 $window.bind( "scroll", checkLoaderPosition );
7576 hidePageLoadingMsg: function() {
7577 $html.removeClass( "ui-loading" );
7579 if( $.mobile.loadingMessage ){
7580 $loader.removeClass( "ui-loader-fakefix" );
7583 $( window ).unbind( "scroll", fakeFixLoader );
7584 $( window ).unbind( "scroll", checkLoaderPosition );
7587 // find and enhance the pages in the dom and transition to the first page.
7588 initializePage: function() {
7589 // find present pages
7590 var $pages = $( ":jqmData(role='page'), :jqmData(role='dialog')" );
7592 // if no pages are found, create one with body's inner html
7593 if ( !$pages.length ) {
7594 $pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 );
7597 // add dialogs, set data-url attrs
7598 $pages.each(function() {
7599 var $this = $(this);
7601 // unless the data url is already set set it to the pathname
7602 if ( !$this.jqmData("url") ) {
7603 $this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) || location.pathname + location.search );
7607 // define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback)
7608 $.mobile.firstPage = $pages.first();
7610 // define page container
7611 $.mobile.pageContainer = $pages.first().parent().addClass( "ui-mobile-viewport" );
7613 // alert listeners that the pagecontainer has been determined for binding
7614 // to events triggered on it
7615 $window.trigger( "pagecontainercreate" );
7617 // cue page loading message
7618 $.mobile.showPageLoadingMsg();
7620 //remove initial build class (only present on first pageshow)
7621 hideRenderingClass();
7623 // if hashchange listening is disabled, there's no hash deeplink,
7624 // the hash is not valid (contains more than one # or does not start with #)
7625 // or there is no page with that hash, change to the first page in the DOM
7626 // Remember, however, that the hash can also be a path!
7627 if ( ! ( $.mobile.hashListeningEnabled &&
7628 $.mobile.path.isHashValid( location.hash ) &&
7629 ( $( location.hash + ':jqmData(role="page")' ).length ||
7630 $.mobile.path.isPath( location.hash ) ) ) ) {
7631 $.mobile.changePage( $.mobile.firstPage, { transition: "none", reverse: true, changeHash: false, fromHashChange: true } );
7633 // otherwise, trigger a hashchange to load a deeplink
7635 $window.trigger( "hashchange", [ true ] );
7640 // initialize events now, after mobileinit has occurred
7641 $.mobile.navreadyDeferred.resolve();
7643 // check which scrollTop value should be used by scrolling to 1 immediately at domready
7644 // then check what the scroll top is. Android will report 0... others 1
7645 // note that this initial scroll won't hide the address bar. It's just for the check.
7647 window.scrollTo( 0, 1 );
7649 // if defaultHomeScroll hasn't been set yet, see if scrollTop is 1
7650 // it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar)
7651 // so if it's 1, use 0 from now on
7652 $.mobile.defaultHomeScroll = ( !$.support.scrollTop || $(window).scrollTop() === 1 ) ? 0 : 1;
7655 // TODO: Implement a proper registration mechanism with dependency handling in order to not have exceptions like the one below
7656 //auto self-init widgets for those widgets that have a soft dependency on others
7657 if ( $.fn.controlgroup ) {
7658 $( document ).bind( "pagecreate create", function( e ){
7659 $( ":jqmData(role='controlgroup')", e.target )
7661 .controlgroup({ excludeInvisible: false });
7666 if( $.mobile.autoInitializePage ){
7667 $.mobile.initializePage();
7670 // window load event
7671 // hide iOS browser chrome on load
7672 $window.load( $.mobile.silentScroll );
7674 if ( !$.support.cssPointerEvents ) {
7675 // IE and Opera don't support CSS pointer-events: none that we use to disable link-based buttons
7676 // by adding the 'ui-disabled' class to them. Using a JavaScript workaround for those browser.
7677 // https://github.com/jquery/jquery-mobile/issues/3558
7679 $( document ).delegate( ".ui-disabled", "vclick",
7682 e.stopImmediatePropagation();