3 * Git HEAD hash: 74b4bec049fd93e4fe40205e6157de16eb64eb46 <> Date: Mon Apr 8 2013 19:41:28 UTC
4 * http://jquerymobile.com
6 * Copyright 2010, 2013 jQuery Foundation, Inc. and other contributors
7 * Released under the MIT license.
8 * http://jquery.org/license
13 (function ( root, doc, factory ) {
14 if ( typeof define === "function" && define.amd ) {
15 // AMD. Register as an anonymous module.
16 define( [ "jquery" ], function ( $ ) {
17 factory( $, root, doc );
22 factory( root.jQuery, root, doc );
24 }( this, document, function ( jQuery, window, document, undefined ) {
28 (function( $, window, undefined ) {
29 var nsNormalizeDict = {};
31 // jQuery.mobile configurable options
32 $.mobile = $.extend($.mobile, {
34 // Version of the jQuery Mobile Framework
37 // Namespace used framework-wide for data-attrs. Default is no namespace
40 // Define the url parameter used for referencing widget-generated sub-pages.
41 // Translates to to example.html&ui-page=subpageIdentifier
42 // hash segment before &ui-page= is used to make Ajax request
43 subPageUrlKey: "ui-page",
45 // Class assigned to page currently in view, and during transitions
46 activePageClass: "ui-page-active",
48 // Class used for "active" button state, from CSS framework
49 activeBtnClass: "ui-btn-active",
51 // Class used for "focus" form element state, from CSS framework
52 focusClass: "ui-focus",
54 // Automatically handle clicks and form submissions through Ajax, when same-domain
57 // Automatically load and show pages based on location.hash
58 hashListeningEnabled: true,
60 // disable to prevent jquery from bothering with links
61 linkBindingEnabled: true,
63 // Set default page transition - 'none' for no transitions
64 defaultPageTransition: "fade",
66 // Set maximum window width for transitions to apply - 'false' for no limit
67 maxTransitionWidth: false,
69 // Minimum scroll distance that will be remembered when returning to a page
72 // DEPRECATED: the following property is no longer in use, but defined until 2.0 to prevent conflicts
73 touchOverflowEnabled: false,
75 // Set default dialog transition - 'none' for no transitions
76 defaultDialogTransition: "pop",
78 // Error response message - appears when an Ajax page request fails
79 pageLoadErrorMessage: "Error Loading Page",
81 // For error messages, which theme does the box uses?
82 pageLoadErrorMessageTheme: "e",
84 // replace calls to window.history.back with phonegaps navigation helper
85 // where it is provided on the window object
86 phonegapNavigationEnabled: false,
88 //automatically initialize the DOM when it's ready
89 autoInitializePage: true,
91 pushStateEnabled: true,
93 // allows users to opt in to ignoring content by marking a parent element as
95 ignoreContentEnabled: false,
97 // turn of binding to the native orientationchange due to android orientation behavior
98 orientationChangeEnabled: true,
104 // define the window and the document objects
106 document: $( document ),
108 // TODO might be useful upstream in jquery itself ?
115 COMMAND_LEFT: 91, // COMMAND
126 MENU: 93, // COMMAND_RIGHT
131 NUMPAD_MULTIPLY: 106,
132 NUMPAD_SUBTRACT: 109,
141 WINDOWS: 91 // COMMAND
144 // Place to store various widget extensions
147 // Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value
148 silentScroll: function( ypos ) {
149 if ( $.type( ypos ) !== "number" ) {
150 ypos = $.mobile.defaultHomeScroll;
153 // prevent scrollstart and scrollstop events
154 $.event.special.scrollstart.enabled = false;
156 setTimeout( function() {
157 window.scrollTo( 0, ypos );
158 $.mobile.document.trigger( "silentscroll", { x: 0, y: ypos });
161 setTimeout( function() {
162 $.event.special.scrollstart.enabled = true;
166 // Expose our cache for testing purposes.
167 nsNormalizeDict: nsNormalizeDict,
169 // Take a data attribute property, prepend the namespace
170 // and then camel case the attribute string. Add the result
171 // to our nsNormalizeDict so we don't have to do this again.
172 nsNormalize: function( prop ) {
177 return nsNormalizeDict[ prop ] || ( nsNormalizeDict[ prop ] = $.camelCase( $.mobile.ns + prop ) );
180 // Find the closest parent with a theme class on it. Note that
181 // we are not using $.fn.closest() on purpose here because this
182 // method gets called quite a bit and we need it to be as fast
184 getInheritedTheme: function( el, defaultTheme ) {
187 re = /ui-(bar|body|overlay)-([a-z])\b/,
191 c = e.className || "";
192 if ( c && ( m = re.exec( c ) ) && ( ltr = m[ 2 ] ) ) {
193 // We found a parent with a theme class
194 // on it so bail from this loop.
201 // Return the theme letter we found, if none, return the
202 // specified default.
204 return ltr || defaultTheme || "a";
207 // TODO the following $ and $.fn extensions can/probably should be moved into jquery.mobile.core.helpers
209 // Find the closest javascript page element to gather settings data jsperf test
210 // http://jsperf.com/single-complex-selector-vs-many-complex-selectors/edit
211 // possibly naive, but it shows that the parsing overhead for *just* the page selector vs
212 // the page and dialog selector is negligable. This could probably be speed up by
213 // doing a similar parent node traversal to the one found in the inherited theme code above
214 closestPageData: function( $target ) {
216 .closest( ':jqmData(role="page"), :jqmData(role="dialog")' )
217 .data( "mobile-page" );
220 enhanceable: function( $set ) {
221 return this.haveParents( $set, "enhance" );
224 hijackable: function( $set ) {
225 return this.haveParents( $set, "ajax" );
228 haveParents: function( $set, attr ) {
229 if ( !$.mobile.ignoreContentEnabled ) {
233 var count = $set.length,
235 e, $element, excluded;
237 for ( var i = 0; i < count; i++ ) {
238 $element = $set.eq( i );
243 var c = e.getAttribute ? e.getAttribute( "data-" + $.mobile.ns + attr ) : "";
245 if ( c === "false" ) {
254 $newSet = $newSet.add( $element );
261 getScreenHeight: function() {
262 // Native innerHeight returns more accurate value for this across platforms,
263 // jQuery version is here as a normalized fallback for platforms like Symbian
264 return window.innerHeight || $.mobile.window.height();
268 // Mobile version of data and removeData and hasData methods
269 // ensures all data is set and retrieved using jQuery Mobile's data namespace
270 $.fn.jqmData = function( prop, value ) {
272 if ( typeof prop !== "undefined" ) {
274 prop = $.mobile.nsNormalize( prop );
277 // undefined is permitted as an explicit input for the second param
278 // in this case it returns the value and does not set it to undefined
279 if( arguments.length < 2 || value === undefined ){
280 result = this.data( prop );
282 result = this.data( prop, value );
288 $.jqmData = function( elem, prop, value ) {
290 if ( typeof prop !== "undefined" ) {
291 result = $.data( elem, prop ? $.mobile.nsNormalize( prop ) : prop, value );
296 $.fn.jqmRemoveData = function( prop ) {
297 return this.removeData( $.mobile.nsNormalize( prop ) );
300 $.jqmRemoveData = function( elem, prop ) {
301 return $.removeData( elem, $.mobile.nsNormalize( prop ) );
304 $.fn.removeWithDependents = function() {
305 $.removeWithDependents( this );
308 $.removeWithDependents = function( elem ) {
309 var $elem = $( elem );
311 ( $elem.jqmData( 'dependents' ) || $() ).remove();
315 $.fn.addDependents = function( newDependents ) {
316 $.addDependents( $( this ), newDependents );
319 $.addDependents = function( elem, newDependents ) {
320 var dependents = $( elem ).jqmData( 'dependents' ) || $();
322 $( elem ).jqmData( 'dependents', $.merge( dependents, newDependents ) );
325 // note that this helper doesn't attempt to handle the callback
326 // or setting of an html element's text, its only purpose is
327 // to return the html encoded version of the text in all cases. (thus the name)
328 $.fn.getEncodedText = function() {
329 return $( "<div/>" ).text( $( this ).text() ).html();
332 // fluent helper function for the mobile namespaced equivalent
333 $.fn.jqmEnhanceable = function() {
334 return $.mobile.enhanceable( this );
337 $.fn.jqmHijackable = function() {
338 return $.mobile.hijackable( this );
341 // Monkey-patching Sizzle to filter the :jqmData selector
342 var oldFind = $.find,
343 jqmDataRE = /:jqmData\(([^)]*)\)/g;
345 $.find = function( selector, context, ret, extra ) {
346 selector = selector.replace( jqmDataRE, "[data-" + ( $.mobile.ns || "" ) + "$1]" );
348 return oldFind.call( this, selector, context, ret, extra );
351 $.extend( $.find, oldFind );
353 $.find.matches = function( expr, set ) {
354 return $.find( expr, null, null, set );
357 $.find.matchesSelector = function( node, expr ) {
358 return $.find( expr, null, null, [ node ] ).length > 0;
364 * jQuery UI Widget v1.10.0pre - 2012-11-13 (ff055a0c353c3c8ce6e5bfa07ad7cb03e8885bc5)
365 * http://jqueryui.com
367 * Copyright 2010, 2013 jQuery Foundation and other contributors
368 * Released under the MIT license.
369 * http://jquery.org/license
371 * http://api.jqueryui.com/jQuery.widget/
373 (function( $, undefined ) {
376 slice = Array.prototype.slice,
377 _cleanData = $.cleanData;
378 $.cleanData = function( elems ) {
379 for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
381 $( elem ).triggerHandler( "remove" );
382 // http://bugs.jquery.com/ticket/8235
388 $.widget = function( name, base, prototype ) {
389 var fullName, existingConstructor, constructor, basePrototype,
390 namespace = name.split( "." )[ 0 ];
392 name = name.split( "." )[ 1 ];
393 fullName = namespace + "-" + name;
400 // create selector for plugin
401 $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
402 return !!$.data( elem, fullName );
405 $[ namespace ] = $[ namespace ] || {};
406 existingConstructor = $[ namespace ][ name ];
407 constructor = $[ namespace ][ name ] = function( options, element ) {
408 // allow instantiation without "new" keyword
409 if ( !this._createWidget ) {
410 return new constructor( options, element );
413 // allow instantiation without initializing for simple inheritance
414 // must use "new" keyword (the code above always passes args)
415 if ( arguments.length ) {
416 this._createWidget( options, element );
419 // extend with the existing constructor to carry over any static properties
420 $.extend( constructor, existingConstructor, {
421 version: prototype.version,
422 // copy the object used to create the prototype in case we need to
423 // redefine the widget later
424 _proto: $.extend( {}, prototype ),
425 // track widgets that inherit from this widget in case this widget is
426 // redefined after a widget inherits from it
427 _childConstructors: []
430 basePrototype = new base();
431 // we need to make the options hash a property directly on the new instance
432 // otherwise we'll modify the options hash on the prototype that we're
434 basePrototype.options = $.widget.extend( {}, basePrototype.options );
435 $.each( prototype, function( prop, value ) {
436 if ( $.isFunction( value ) ) {
437 prototype[ prop ] = (function() {
438 var _super = function() {
439 return base.prototype[ prop ].apply( this, arguments );
441 _superApply = function( args ) {
442 return base.prototype[ prop ].apply( this, args );
445 var __super = this._super,
446 __superApply = this._superApply,
449 this._super = _super;
450 this._superApply = _superApply;
452 returnValue = value.apply( this, arguments );
454 this._super = __super;
455 this._superApply = __superApply;
462 constructor.prototype = $.widget.extend( basePrototype, {
463 // TODO: remove support for widgetEventPrefix
464 // always use the name + a colon as the prefix, e.g., draggable:start
465 // don't prefix for widgets that aren't DOM-based
466 widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name
468 constructor: constructor,
469 namespace: namespace,
471 widgetFullName: fullName
474 // If this widget is being redefined then we need to find all widgets that
475 // are inheriting from it and redefine all of them so that they inherit from
476 // the new version of this widget. We're essentially trying to replace one
477 // level in the prototype chain.
478 if ( existingConstructor ) {
479 $.each( existingConstructor._childConstructors, function( i, child ) {
480 var childPrototype = child.prototype;
482 // redefine the child widget using the same prototype that was
483 // originally used, but inherit from the new version of the base
484 $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
486 // remove the list of existing child constructors from the old constructor
487 // so the old child constructors can be garbage collected
488 delete existingConstructor._childConstructors;
490 base._childConstructors.push( constructor );
493 $.widget.bridge( name, constructor );
496 $.widget.extend = function( target ) {
497 var input = slice.call( arguments, 1 ),
499 inputLength = input.length,
502 for ( ; inputIndex < inputLength; inputIndex++ ) {
503 for ( key in input[ inputIndex ] ) {
504 value = input[ inputIndex ][ key ];
505 if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
507 if ( $.isPlainObject( value ) ) {
508 target[ key ] = $.isPlainObject( target[ key ] ) ?
509 $.widget.extend( {}, target[ key ], value ) :
510 // Don't extend strings, arrays, etc. with objects
511 $.widget.extend( {}, value );
512 // Copy everything else by reference
514 target[ key ] = value;
522 $.widget.bridge = function( name, object ) {
523 var fullName = object.prototype.widgetFullName || name;
524 $.fn[ name ] = function( options ) {
525 var isMethodCall = typeof options === "string",
526 args = slice.call( arguments, 1 ),
529 // allow multiple hashes to be passed on init
530 options = !isMethodCall && args.length ?
531 $.widget.extend.apply( null, [ options ].concat(args) ) :
534 if ( isMethodCall ) {
535 this.each(function() {
537 instance = $.data( this, fullName );
539 return $.error( "cannot call methods on " + name + " prior to initialization; " +
540 "attempted to call method '" + options + "'" );
542 if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
543 return $.error( "no such method '" + options + "' for " + name + " widget instance" );
545 methodValue = instance[ options ].apply( instance, args );
546 if ( methodValue !== instance && methodValue !== undefined ) {
547 returnValue = methodValue && methodValue.jquery ?
548 returnValue.pushStack( methodValue.get() ) :
554 this.each(function() {
555 var instance = $.data( this, fullName );
557 instance.option( options || {} )._init();
559 $.data( this, fullName, new object( options, this ) );
568 $.Widget = function( /* options, element */ ) {};
569 $.Widget._childConstructors = [];
571 $.Widget.prototype = {
572 widgetName: "widget",
573 widgetEventPrefix: "",
574 defaultElement: "<div>",
581 _createWidget: function( options, element ) {
582 element = $( element || this.defaultElement || this )[ 0 ];
583 this.element = $( element );
585 this.eventNamespace = "." + this.widgetName + this.uuid;
586 this.options = $.widget.extend( {},
588 this._getCreateOptions(),
592 this.hoverable = $();
593 this.focusable = $();
595 if ( element !== this ) {
596 $.data( element, this.widgetFullName, this );
597 this._on( true, this.element, {
598 remove: function( event ) {
599 if ( event.target === element ) {
604 this.document = $( element.style ?
605 // element within the document
606 element.ownerDocument :
607 // element is window or document
608 element.document || element );
609 this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
613 this._trigger( "create", null, this._getCreateEventData() );
616 _getCreateOptions: $.noop,
617 _getCreateEventData: $.noop,
621 destroy: function() {
623 // we can probably remove the unbind calls in 2.0
624 // all event bindings should go through this._on()
626 .unbind( this.eventNamespace )
628 // TODO remove dual storage
629 .removeData( this.widgetName )
630 .removeData( this.widgetFullName )
631 // support: jquery <1.6.3
632 // http://bugs.jquery.com/ticket/9413
633 .removeData( $.camelCase( this.widgetFullName ) );
635 .unbind( this.eventNamespace )
636 .removeAttr( "aria-disabled" )
638 this.widgetFullName + "-disabled " +
639 "ui-state-disabled" );
641 // clean up events and states
642 this.bindings.unbind( this.eventNamespace );
643 this.hoverable.removeClass( "ui-state-hover" );
644 this.focusable.removeClass( "ui-state-focus" );
652 option: function( key, value ) {
658 if ( arguments.length === 0 ) {
659 // don't return a reference to the internal hash
660 return $.widget.extend( {}, this.options );
663 if ( typeof key === "string" ) {
664 // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
666 parts = key.split( "." );
668 if ( parts.length ) {
669 curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
670 for ( i = 0; i < parts.length - 1; i++ ) {
671 curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
672 curOption = curOption[ parts[ i ] ];
675 if ( value === undefined ) {
676 return curOption[ key ] === undefined ? null : curOption[ key ];
678 curOption[ key ] = value;
680 if ( value === undefined ) {
681 return this.options[ key ] === undefined ? null : this.options[ key ];
683 options[ key ] = value;
687 this._setOptions( options );
691 _setOptions: function( options ) {
694 for ( key in options ) {
695 this._setOption( key, options[ key ] );
700 _setOption: function( key, value ) {
701 this.options[ key ] = value;
703 if ( key === "disabled" ) {
705 .toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
706 .attr( "aria-disabled", value );
707 this.hoverable.removeClass( "ui-state-hover" );
708 this.focusable.removeClass( "ui-state-focus" );
715 return this._setOption( "disabled", false );
717 disable: function() {
718 return this._setOption( "disabled", true );
721 _on: function( suppressDisabledCheck, element, handlers ) {
725 // no suppressDisabledCheck flag, shuffle arguments
726 if ( typeof suppressDisabledCheck !== "boolean" ) {
728 element = suppressDisabledCheck;
729 suppressDisabledCheck = false;
732 // no element argument, shuffle and use this.element
735 element = this.element;
736 delegateElement = this.widget();
738 // accept selectors, DOM elements
739 element = delegateElement = $( element );
740 this.bindings = this.bindings.add( element );
743 $.each( handlers, function( event, handler ) {
744 function handlerProxy() {
745 // allow widgets to customize the disabled handling
746 // - disabled as an array instead of boolean
747 // - disabled class as method for disabling individual parts
748 if ( !suppressDisabledCheck &&
749 ( instance.options.disabled === true ||
750 $( this ).hasClass( "ui-state-disabled" ) ) ) {
753 return ( typeof handler === "string" ? instance[ handler ] : handler )
754 .apply( instance, arguments );
757 // copy the guid so direct unbinding works
758 if ( typeof handler !== "string" ) {
759 handlerProxy.guid = handler.guid =
760 handler.guid || handlerProxy.guid || $.guid++;
763 var match = event.match( /^(\w+)\s*(.*)$/ ),
764 eventName = match[1] + instance.eventNamespace,
767 delegateElement.delegate( selector, eventName, handlerProxy );
769 element.bind( eventName, handlerProxy );
774 _off: function( element, eventName ) {
775 eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
776 element.unbind( eventName ).undelegate( eventName );
779 _delay: function( handler, delay ) {
780 function handlerProxy() {
781 return ( typeof handler === "string" ? instance[ handler ] : handler )
782 .apply( instance, arguments );
785 return setTimeout( handlerProxy, delay || 0 );
788 _hoverable: function( element ) {
789 this.hoverable = this.hoverable.add( element );
791 mouseenter: function( event ) {
792 $( event.currentTarget ).addClass( "ui-state-hover" );
794 mouseleave: function( event ) {
795 $( event.currentTarget ).removeClass( "ui-state-hover" );
800 _focusable: function( element ) {
801 this.focusable = this.focusable.add( element );
803 focusin: function( event ) {
804 $( event.currentTarget ).addClass( "ui-state-focus" );
806 focusout: function( event ) {
807 $( event.currentTarget ).removeClass( "ui-state-focus" );
812 _trigger: function( type, event, data ) {
814 callback = this.options[ type ];
817 event = $.Event( event );
818 event.type = ( type === this.widgetEventPrefix ?
820 this.widgetEventPrefix + type ).toLowerCase();
821 // the original event may come from any element
822 // so we need to reset the target on the new event
823 event.target = this.element[ 0 ];
825 // copy original event properties over to the new event
826 orig = event.originalEvent;
828 for ( prop in orig ) {
829 if ( !( prop in event ) ) {
830 event[ prop ] = orig[ prop ];
835 this.element.trigger( event, data );
836 return !( $.isFunction( callback ) &&
837 callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
838 event.isDefaultPrevented() );
842 $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
843 $.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
844 if ( typeof options === "string" ) {
845 options = { effect: options };
848 effectName = !options ?
850 options === true || typeof options === "number" ?
852 options.effect || defaultEffect;
853 options = options || {};
854 if ( typeof options === "number" ) {
855 options = { duration: options };
857 hasOptions = !$.isEmptyObject( options );
858 options.complete = callback;
859 if ( options.delay ) {
860 element.delay( options.delay );
862 if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
863 element[ method ]( options );
864 } else if ( effectName !== method && element[ effectName ] ) {
865 element[ effectName ]( options.duration, options.easing, callback );
867 element.queue(function( next ) {
868 $( this )[ method ]();
870 callback.call( element[ 0 ] );
880 (function( $, undefined ) {
882 $.widget( "mobile.widget", {
883 // decorate the parent _createWidget to trigger `widgetinit` for users
884 // who wish to do post post `widgetcreate` alterations/additions
886 // TODO create a pull request for jquery ui to trigger this event
887 // in the original _createWidget
888 _createWidget: function() {
889 $.Widget.prototype._createWidget.apply( this, arguments );
890 this._trigger( 'init' );
893 _getCreateOptions: function() {
895 var elem = this.element,
898 $.each( this.options, function( option ) {
900 var value = elem.jqmData( option.replace( /[A-Z]/g, function( c ) {
901 return "-" + c.toLowerCase();
905 if ( value !== undefined ) {
906 options[ option ] = value;
913 enhanceWithin: function( target, useKeepNative ) {
914 this.enhance( $( this.options.initSelector, $( target )), useKeepNative );
917 enhance: function( targets, useKeepNative ) {
918 var page, keepNative, $widgetElements = $( targets ), self = this;
920 // if ignoreContentEnabled is set to true the framework should
921 // only enhance the selected elements when they do NOT have a
922 // parent with the data-namespace-ignore attribute
923 $widgetElements = $.mobile.enhanceable( $widgetElements );
925 if ( useKeepNative && $widgetElements.length ) {
926 // TODO remove dependency on the page widget for the keepNative.
927 // Currently the keepNative value is defined on the page prototype so
928 // the method is as well
929 page = $.mobile.closestPageData( $widgetElements );
930 keepNative = ( page && page.keepNativeSelector()) || "";
932 $widgetElements = $widgetElements.not( keepNative );
935 $widgetElements[ this.widgetName ]();
938 raise: function( msg ) {
939 throw "Widget [" + this.widgetName + "]: " + msg;
946 (function( $, window ) {
948 // NOTE global mobile object settings
949 $.extend( $.mobile, {
950 // DEPRECATED Should the text be visble in the loading message?
951 loadingMessageTextVisible: undefined,
953 // DEPRECATED When the text is visible, what theme does the loading box use?
954 loadingMessageTheme: undefined,
956 // DEPRECATED default message setting
957 loadingMessage: undefined,
960 // Turn on/off page loading message. Theme doubles as an object argument
961 // with the following shape: { theme: '', text: '', html: '', textVisible: '' }
962 // NOTE that the $.mobile.loading* settings and params past the first are deprecated
963 showPageLoadingMsg: function( theme, msgText, textonly ) {
964 $.mobile.loading( 'show', theme, msgText, textonly );
968 hidePageLoadingMsg: function() {
969 $.mobile.loading( 'hide' );
972 loading: function() {
973 this.loaderWidget.loader.apply( this.loaderWidget, arguments );
977 // TODO move loader class down into the widget settings
978 var loaderClass = "ui-loader", $html = $( "html" ), $window = $.mobile.window;
980 $.widget( "mobile.loader", {
981 // NOTE if the global config settings are defined they will override these
984 // the theme for the loading message
987 // whether the text in the loading message is shown
990 // custom html for the inner content of the loading message
993 // the text to be displayed when the popup is shown
997 defaultHtml: "<div class='" + loaderClass + "'>" +
998 "<span class='ui-icon ui-icon-loading'></span>" +
1002 // For non-fixed supportin browsers. Position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top
1003 fakeFixLoader: function() {
1004 var activeBtn = $( "." + $.mobile.activeBtnClass ).first();
1008 top: $.support.scrollTop && $window.scrollTop() + $window.height() / 2 ||
1009 activeBtn.length && activeBtn.offset().top || 100
1013 // check position of loader to see if it appears to be "fixed" to center
1014 // if not, use abs positioning
1015 checkLoaderPosition: function() {
1016 var offset = this.element.offset(),
1017 scrollTop = $window.scrollTop(),
1018 screenHeight = $.mobile.getScreenHeight();
1020 if ( offset.top < scrollTop || ( offset.top - scrollTop ) > screenHeight ) {
1021 this.element.addClass( "ui-loader-fakefix" );
1022 this.fakeFixLoader();
1024 .unbind( "scroll", this.checkLoaderPosition )
1025 .bind( "scroll", $.proxy( this.fakeFixLoader, this ) );
1029 resetHtml: function() {
1030 this.element.html( $( this.defaultHtml ).html() );
1033 // Turn on/off page loading message. Theme doubles as an object argument
1034 // with the following shape: { theme: '', text: '', html: '', textVisible: '' }
1035 // NOTE that the $.mobile.loading* settings and params past the first are deprecated
1036 // TODO sweet jesus we need to break some of this out
1037 show: function( theme, msgText, textonly ) {
1038 var textVisible, message, $header, loadSettings;
1042 // use the prototype options so that people can set them globally at
1043 // mobile init. Consistency, it's what's for dinner
1044 if ( $.type(theme) === "object" ) {
1045 loadSettings = $.extend( {}, this.options, theme );
1047 // prefer object property from the param then the old theme setting
1048 theme = loadSettings.theme || $.mobile.loadingMessageTheme;
1050 loadSettings = this.options;
1052 // here we prefer the them value passed as a string argument, then
1053 // we prefer the global option because we can't use undefined default
1054 // prototype options, then the prototype option
1055 theme = theme || $.mobile.loadingMessageTheme || loadSettings.theme;
1058 // set the message text, prefer the param, then the settings object
1059 // then loading message
1060 message = msgText || $.mobile.loadingMessage || loadSettings.text;
1063 $html.addClass( "ui-loading" );
1065 if ( $.mobile.loadingMessage !== false || loadSettings.html ) {
1066 // boolean values require a bit more work :P, supports object properties
1068 if ( $.mobile.loadingMessageTextVisible !== undefined ) {
1069 textVisible = $.mobile.loadingMessageTextVisible;
1071 textVisible = loadSettings.textVisible;
1074 // add the proper css given the options (theme, text, etc)
1075 // Force text visibility if the second argument was supplied, or
1076 // if the text was explicitly set in the object args
1077 this.element.attr("class", loaderClass +
1078 " ui-corner-all ui-body-" + theme +
1079 " ui-loader-" + ( textVisible || msgText || theme.text ? "verbose" : "default" ) +
1080 ( loadSettings.textonly || textonly ? " ui-loader-textonly" : "" ) );
1082 // TODO verify that jquery.fn.html is ok to use in both cases here
1083 // this might be overly defensive in preventing unknowing xss
1084 // if the html attribute is defined on the loading settings, use that
1085 // otherwise use the fallbacks from above
1086 if ( loadSettings.html ) {
1087 this.element.html( loadSettings.html );
1089 this.element.find( "h1" ).text( message );
1092 // attach the loader to the DOM
1093 this.element.appendTo( $.mobile.pageContainer );
1095 // check that the loader is visible
1096 this.checkLoaderPosition();
1098 // on scroll check the loader position
1099 $window.bind( "scroll", $.proxy( this.checkLoaderPosition, this ) );
1104 $html.removeClass( "ui-loading" );
1106 if ( $.mobile.loadingMessage ) {
1107 this.element.removeClass( "ui-loader-fakefix" );
1110 $.mobile.window.unbind( "scroll", this.fakeFixLoader );
1111 $.mobile.window.unbind( "scroll", this.checkLoaderPosition );
1115 $window.bind( 'pagecontainercreate', function() {
1116 $.mobile.loaderWidget = $.mobile.loaderWidget || $( $.mobile.loader.prototype.defaultHtml ).loader();
1121 // Script: jQuery hashchange event
1123 // *Version: 1.3, Last updated: 7/21/2010*
1125 // Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
1126 // GitHub - http://github.com/cowboy/jquery-hashchange/
1127 // Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
1128 // (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped)
1132 // Copyright (c) 2010 "Cowboy" Ben Alman,
1133 // Dual licensed under the MIT and GPL licenses.
1134 // http://benalman.com/about/license/
1138 // These working examples, complete with fully commented code, illustrate a few
1139 // ways in which this plugin can be used.
1141 // hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
1142 // document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/
1144 // About: Support and Testing
1146 // Information about what version or versions of jQuery this plugin has been
1147 // tested with, what browsers it has been tested in, and where the unit tests
1148 // reside (so you can test it yourself).
1150 // jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2
1151 // Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5,
1152 // Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5.
1153 // Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/
1155 // About: Known issues
1157 // While this jQuery hashchange event implementation is quite stable and
1158 // robust, there are a few unfortunate browser bugs surrounding expected
1159 // hashchange event-based behaviors, independent of any JavaScript
1160 // window.onhashchange abstraction. See the following examples for more
1163 // Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
1164 // Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
1165 // WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
1166 // Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
1168 // Also note that should a browser natively support the window.onhashchange
1169 // event, but not report that it does, the fallback polling loop will be used.
1171 // About: Release History
1173 // 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more
1174 // "removable" for mobile-only development. Added IE6/7 document.title
1175 // support. Attempted to make Iframe as hidden as possible by using
1176 // techniques from http://www.paciellogroup.com/blog/?p=604. Added
1177 // support for the "shortcut" format $(window).hashchange( fn ) and
1178 // $(window).hashchange() like jQuery provides for built-in events.
1179 // Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and
1180 // lowered its default value to 50. Added <jQuery.fn.hashchange.domain>
1181 // and <jQuery.fn.hashchange.src> properties plus document-domain.html
1182 // file to address access denied issues when setting document.domain in
1184 // 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin
1185 // from a page on another domain would cause an error in Safari 4. Also,
1186 // IE6/7 Iframe is now inserted after the body (this actually works),
1187 // which prevents the page from scrolling when the event is first bound.
1188 // Event can also now be bound before DOM ready, but it won't be usable
1189 // before then in IE6/7.
1190 // 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
1191 // where browser version is incorrectly reported as 8.0, despite
1192 // inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
1193 // 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
1194 // window.onhashchange functionality into a separate plugin for users
1195 // who want just the basic event & back button support, without all the
1196 // extra awesomeness that BBQ provides. This plugin will be included as
1197 // part of jQuery BBQ, but also be available separately.
1199 (function( $, window, undefined ) {
1201 var str_hashchange = 'hashchange',
1203 // Method / object references.
1206 special = $.event.special,
1208 // Does the browser support window.onhashchange? Note that IE8 running in
1209 // IE7 compatibility mode reports true for 'onhashchange' in window, even
1210 // though the event isn't supported, so also test document.documentMode.
1211 doc_mode = doc.documentMode,
1212 supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 );
1214 // Get location.hash (or what you'd expect location.hash to be) sans any
1215 // leading #. Thanks for making this necessary, Firefox!
1216 function get_fragment( url ) {
1217 url = url || location.href;
1218 return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
1221 // Method: jQuery.fn.hashchange
1223 // Bind a handler to the window.onhashchange event or trigger all bound
1224 // window.onhashchange event handlers. This behavior is consistent with
1225 // jQuery's built-in event handlers.
1229 // > jQuery(window).hashchange( [ handler ] );
1233 // handler - (Function) Optional handler to be bound to the hashchange
1234 // event. This is a "shortcut" for the more verbose form:
1235 // jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
1236 // all bound window.onhashchange event handlers will be triggered. This
1237 // is a shortcut for the more verbose
1238 // jQuery(window).trigger( 'hashchange' ). These forms are described in
1239 // the <hashchange event> section.
1243 // (jQuery) The initial jQuery collection of elements.
1245 // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
1246 // $(elem).hashchange() for triggering, like jQuery does for built-in events.
1247 $.fn[ str_hashchange ] = function( fn ) {
1248 return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange );
1251 // Property: jQuery.fn.hashchange.delay
1253 // The numeric interval (in milliseconds) at which the <hashchange event>
1254 // polling loop executes. Defaults to 50.
1256 // Property: jQuery.fn.hashchange.domain
1258 // If you're setting document.domain in your JavaScript, and you want hash
1259 // history to work in IE6/7, not only must this property be set, but you must
1260 // also set document.domain BEFORE jQuery is loaded into the page. This
1261 // property is only applicable if you are supporting IE6/7 (or IE8 operating
1262 // in "IE7 compatibility" mode).
1264 // In addition, the <jQuery.fn.hashchange.src> property must be set to the
1265 // path of the included "document-domain.html" file, which can be renamed or
1266 // modified if necessary (note that the document.domain specified must be the
1267 // same in both your main JavaScript as well as in this file).
1271 // jQuery.fn.hashchange.domain = document.domain;
1273 // Property: jQuery.fn.hashchange.src
1275 // If, for some reason, you need to specify an Iframe src file (for example,
1276 // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can
1277 // do so using this property. Note that when using this property, history
1278 // won't be recorded in IE6/7 until the Iframe src file loads. This property
1279 // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7
1280 // compatibility" mode).
1284 // jQuery.fn.hashchange.src = 'path/to/file.html';
1286 $.fn[ str_hashchange ].delay = 50;
1288 $.fn[ str_hashchange ].domain = null;
1289 $.fn[ str_hashchange ].src = null;
1292 // Event: hashchange event
1294 // Fired when location.hash changes. In browsers that support it, the native
1295 // HTML5 window.onhashchange event is used, otherwise a polling loop is
1296 // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to
1297 // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7
1298 // compatibility" mode), a hidden Iframe is created to allow the back button
1299 // and hash-based history to work.
1301 // Usage as described in <jQuery.fn.hashchange>:
1303 // > // Bind an event handler.
1304 // > jQuery(window).hashchange( function(e) {
1305 // > var hash = location.hash;
1309 // > // Manually trigger the event handler.
1310 // > jQuery(window).hashchange();
1312 // A more verbose usage that allows for event namespacing:
1314 // > // Bind an event handler.
1315 // > jQuery(window).bind( 'hashchange', function(e) {
1316 // > var hash = location.hash;
1320 // > // Manually trigger the event handler.
1321 // > jQuery(window).trigger( 'hashchange' );
1323 // Additional Notes:
1325 // * The polling loop and Iframe are not created until at least one handler
1326 // is actually bound to the 'hashchange' event.
1327 // * If you need the bound handler(s) to execute immediately, in cases where
1328 // a location.hash exists on page load, via bookmark or page refresh for
1329 // example, use jQuery(window).hashchange() or the more verbose
1330 // jQuery(window).trigger( 'hashchange' ).
1331 // * The event can be bound before DOM ready, but since it won't be usable
1332 // before then in IE6/7 (due to the necessary Iframe), recommended usage is
1333 // to bind it inside a DOM ready handler.
1335 // Override existing $.event.special.hashchange methods (allowing this plugin
1336 // to be defined after jQuery BBQ in BBQ's source code).
1337 special[ str_hashchange ] = $.extend( special[ str_hashchange ], {
1339 // Called only when the first 'hashchange' event is bound to window.
1341 // If window.onhashchange is supported natively, there's nothing to do..
1342 if ( supports_onhashchange ) { return false; }
1344 // Otherwise, we need to create our own. And we don't want to call this
1345 // until the user binds to the event, just in case they never do, since it
1346 // will create a polling loop and possibly even a hidden Iframe.
1347 $( fake_onhashchange.start );
1350 // Called only when the last 'hashchange' event is unbound from window.
1351 teardown: function() {
1352 // If window.onhashchange is supported natively, there's nothing to do..
1353 if ( supports_onhashchange ) { return false; }
1355 // Otherwise, we need to stop ours (if possible).
1356 $( fake_onhashchange.stop );
1361 // fake_onhashchange does all the work of triggering the window.onhashchange
1362 // event for browsers that don't natively support it, including creating a
1363 // polling loop to watch for hash changes and in IE 6/7 creating a hidden
1364 // Iframe to enable back and forward.
1365 fake_onhashchange = (function() {
1369 // Remember the initial hash so it doesn't get triggered immediately.
1370 last_hash = get_fragment(),
1372 fn_retval = function( val ) { return val; },
1373 history_set = fn_retval,
1374 history_get = fn_retval;
1376 // Start the polling loop.
1377 self.start = function() {
1378 timeout_id || poll();
1381 // Stop the polling loop.
1382 self.stop = function() {
1383 timeout_id && clearTimeout( timeout_id );
1384 timeout_id = undefined;
1387 // This polling loop checks every $.fn.hashchange.delay milliseconds to see
1388 // if location.hash has changed, and triggers the 'hashchange' event on
1389 // window when necessary.
1391 var hash = get_fragment(),
1392 history_hash = history_get( last_hash );
1394 if ( hash !== last_hash ) {
1395 history_set( last_hash = hash, history_hash );
1397 $(window).trigger( str_hashchange );
1399 } else if ( history_hash !== last_hash ) {
1400 location.href = location.href.replace( /#.*/, '' ) + history_hash;
1403 timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay );
1406 // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
1407 // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
1408 // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
1409 window.attachEvent && !window.addEventListener && !supports_onhashchange && (function() {
1410 // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
1411 // when running in "IE7 compatibility" mode.
1416 // When the event is bound and polling starts in IE 6/7, create a hidden
1417 // Iframe for history handling.
1418 self.start = function() {
1420 iframe_src = $.fn[ str_hashchange ].src;
1421 iframe_src = iframe_src && iframe_src + get_fragment();
1423 // Create hidden Iframe. Attempt to make Iframe as hidden as possible
1424 // by using techniques from http://www.paciellogroup.com/blog/?p=604.
1425 iframe = $('<iframe tabindex="-1" title="empty"/>').hide()
1427 // When Iframe has completely loaded, initialize the history and
1429 .one( 'load', function() {
1430 iframe_src || history_set( get_fragment() );
1434 // Load Iframe src if specified, otherwise nothing.
1435 .attr( 'src', iframe_src || 'javascript:0' )
1437 // Append Iframe after the end of the body to prevent unnecessary
1438 // initial page scrolling (yes, this works).
1439 .insertAfter( 'body' )[0].contentWindow;
1441 // Whenever `document.title` changes, update the Iframe's title to
1442 // prettify the back/next history menu entries. Since IE sometimes
1443 // errors with "Unspecified error" the very first time this is set
1444 // (yes, very useful) wrap this with a try/catch block.
1445 doc.onpropertychange = function() {
1447 if ( event.propertyName === 'title' ) {
1448 iframe.document.title = doc.title;
1456 // Override the "stop" method since an IE6/7 Iframe was created. Even
1457 // if there are no longer any bound event handlers, the polling loop
1458 // is still necessary for back/next to work at all!
1459 self.stop = fn_retval;
1461 // Get history by looking at the hidden Iframe's location.hash.
1462 history_get = function() {
1463 return get_fragment( iframe.location.href );
1466 // Set a new history item by opening and then closing the Iframe
1467 // document, *then* setting its location.hash. If document.domain has
1468 // been set, update that as well.
1469 history_set = function( hash, history_hash ) {
1470 var iframe_doc = iframe.document,
1471 domain = $.fn[ str_hashchange ].domain;
1473 if ( hash !== history_hash ) {
1474 // Update Iframe with any initial `document.title` that might be set.
1475 iframe_doc.title = doc.title;
1477 // Opening the Iframe's document after it has been closed is what
1478 // actually adds a history entry.
1481 // Set document.domain for the Iframe document as well, if necessary.
1482 domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' );
1486 // Update the Iframe's hash, for great justice.
1487 iframe.location.hash = hash;
1492 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1493 // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
1494 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1501 (function( $, undefined ) {
1503 /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
1504 window.matchMedia = window.matchMedia || (function( doc, undefined ) {
1509 docElem = doc.documentElement,
1510 refNode = docElem.firstElementChild || docElem.firstChild,
1511 // fakeBody required for <FF4 when executed in <head>
1512 fakeBody = doc.createElement( "body" ),
1513 div = doc.createElement( "div" );
1515 div.id = "mq-test-1";
1516 div.style.cssText = "position:absolute;top:-100em";
1517 fakeBody.style.background = "none";
1518 fakeBody.appendChild(div);
1522 div.innerHTML = "­<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>";
1524 docElem.insertBefore( fakeBody, refNode );
1525 bool = div.offsetWidth === 42;
1526 docElem.removeChild( fakeBody );
1537 // $.mobile.media uses matchMedia to return a boolean.
1538 $.mobile.media = function( q ) {
1539 return window.matchMedia( q ).matches;
1544 (function( $, undefined ) {
1546 touch: "ontouchend" in document
1549 $.mobile.support = $.mobile.support || {};
1550 $.extend( $.support, support );
1551 $.extend( $.mobile.support, support );
1554 (function( $, undefined ) {
1555 $.extend( $.support, {
1556 orientation: "orientation" in window && "onorientationchange" in window
1560 (function( $, undefined ) {
1563 function propExists( prop ) {
1564 var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ),
1565 props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " );
1567 for ( var v in props ) {
1568 if ( fbCSS[ props[ v ] ] !== undefined ) {
1574 var fakeBody = $( "<body>" ).prependTo( "html" ),
1575 fbCSS = fakeBody[ 0 ].style,
1576 vendors = [ "Webkit", "Moz", "O" ],
1577 webos = "palmGetResource" in window, //only used to rule out scrollTop
1578 opera = window.opera,
1579 operamini = window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]",
1580 bb = window.blackberry && !propExists( "-webkit-transform" ); //only used to rule out box shadow, as it's filled opaque on BB 5 and lower
1583 function validStyle( prop, value, check_vend ) {
1584 var div = document.createElement( 'div' ),
1585 uc = function( txt ) {
1586 return txt.charAt( 0 ).toUpperCase() + txt.substr( 1 );
1588 vend_pref = function( vend ) {
1592 return "-" + vend.charAt( 0 ).toLowerCase() + vend.substr( 1 ) + "-";
1595 check_style = function( vend ) {
1596 var vend_prop = vend_pref( vend ) + prop + ": " + value + ";",
1597 uc_vend = uc( vend ),
1598 propStyle = uc_vend + ( uc_vend === "" ? prop : uc( prop ) );
1600 div.setAttribute( "style", vend_prop );
1602 if ( !!div.style[ propStyle ] ) {
1606 check_vends = check_vend ? check_vend : vendors,
1609 for( var i = 0; i < check_vends.length; i++ ) {
1610 check_style( check_vends[i] );
1615 function transform3dTest() {
1616 var mqProp = "transform-3d",
1617 // Because the `translate3d` test below throws false positives in Android:
1618 ret = $.mobile.media( "(-" + vendors.join( "-" + mqProp + "),(-" ) + "-" + mqProp + "),(" + mqProp + ")" );
1624 var el = document.createElement( "div" ),
1626 // We’re omitting Opera for the time being; MS uses unprefixed.
1627 'MozTransform':'-moz-transform',
1628 'transform':'transform'
1631 fakeBody.append( el );
1633 for ( var t in transforms ) {
1634 if( el.style[ t ] !== undefined ){
1635 el.style[ t ] = 'translate3d( 100px, 1px, 1px )';
1636 ret = window.getComputedStyle( el ).getPropertyValue( transforms[ t ] );
1639 return ( !!ret && ret !== "none" );
1642 // Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting )
1643 function baseTagTest() {
1644 var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/",
1645 base = $( "head base" ),
1650 if ( !base.length ) {
1651 base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" );
1653 href = base.attr( "href" );
1656 link = $( "<a href='testurl' />" ).prependTo( fakeBody );
1657 rebase = link[ 0 ].href;
1658 base[ 0 ].href = href || location.pathname;
1663 return rebase.indexOf( fauxBase ) === 0;
1667 function cssPointerEventsTest() {
1668 var element = document.createElement( 'x' ),
1669 documentElement = document.documentElement,
1670 getComputedStyle = window.getComputedStyle,
1673 if ( !( 'pointerEvents' in element.style ) ) {
1677 element.style.pointerEvents = 'auto';
1678 element.style.pointerEvents = 'x';
1679 documentElement.appendChild( element );
1680 supports = getComputedStyle &&
1681 getComputedStyle( element, '' ).pointerEvents === 'auto';
1682 documentElement.removeChild( element );
1686 function boundingRect() {
1687 var div = document.createElement( "div" );
1688 return typeof div.getBoundingClientRect !== "undefined";
1691 // non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683
1692 // allows for inclusion of IE 6+, including Windows Mobile 7
1693 $.extend( $.mobile, { browser: {} } );
1694 $.mobile.browser.oldIE = (function() {
1696 div = document.createElement( "div" ),
1700 div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->";
1703 return v > 4 ? v : !v;
1706 function fixedPosition() {
1708 ua = navigator.userAgent,
1709 platform = navigator.platform,
1710 // Rendering engine is Webkit, and capture major version
1711 wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ),
1712 wkversion = !!wkmatch && wkmatch[ 1 ],
1713 ffmatch = ua.match( /Fennec\/([0-9]+)/ ),
1714 ffversion = !!ffmatch && ffmatch[ 1 ],
1715 operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ ),
1716 omversion = !!operammobilematch && operammobilematch[ 1 ];
1719 // iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5)
1720 ( ( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534 ) ||
1722 ( w.operamini && ({}).toString.call( w.operamini ) === "[object OperaMini]" ) ||
1723 ( operammobilematch && omversion < 7458 ) ||
1724 //Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2)
1725 ( ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533 ) ||
1726 // Firefox Mobile before 6.0 -
1727 ( ffversion && ffversion < 6 ) ||
1728 // WebOS less than 3
1729 ( "palmGetResource" in window && wkversion && wkversion < 534 ) ||
1731 ( ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1 ) ) {
1738 $.extend( $.support, {
1739 cssTransitions: "WebKitTransitionEvent" in window ||
1740 validStyle( 'transition', 'height 100ms linear', [ "Webkit", "Moz", "" ] ) &&
1741 !$.mobile.browser.oldIE && !opera,
1743 // Note, Chrome for iOS has an extremely quirky implementation of popstate.
1744 // We've chosen to take the shortest path to a bug fix here for issue #5426
1745 // See the following link for information about the regex chosen
1746 // https://developers.google.com/chrome/mobile/docs/user-agent#chrome_for_ios_user-agent
1747 pushState: "pushState" in history &&
1748 "replaceState" in history &&
1749 // When running inside a FF iframe, calling replaceState causes an error
1750 !( window.navigator.userAgent.indexOf( "Firefox" ) >= 0 && window.top !== window ) &&
1751 ( window.navigator.userAgent.search(/CriOS/) === -1 ),
1753 mediaquery: $.mobile.media( "only all" ),
1754 cssPseudoElement: !!propExists( "content" ),
1755 touchOverflow: !!propExists( "overflowScrolling" ),
1756 cssTransform3d: transform3dTest(),
1757 boxShadow: !!propExists( "boxShadow" ) && !bb,
1758 fixedPosition: fixedPosition(),
1759 scrollTop: ("pageXOffset" in window ||
1760 "scrollTop" in document.documentElement ||
1761 "scrollTop" in fakeBody[ 0 ]) && !webos && !operamini,
1763 dynamicBaseTag: baseTagTest(),
1764 cssPointerEvents: cssPointerEventsTest(),
1765 boundingRect: boundingRect()
1771 // $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian)
1772 // or that generally work better browsing in regular http for full page refreshes (Opera Mini)
1773 // Note: This detection below is used as a last resort.
1774 // We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible
1775 var nokiaLTE7_3 = (function() {
1777 var ua = window.navigator.userAgent;
1779 //The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older
1780 return ua.indexOf( "Nokia" ) > -1 &&
1781 ( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) &&
1782 ua.indexOf( "AppleWebKit" ) > -1 &&
1783 ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ );
1786 // Support conditions that must be met in order to proceed
1787 // default enhanced qualifications are media query support OR IE 7+
1789 $.mobile.gradeA = function() {
1790 return ( $.support.mediaquery || $.mobile.browser.oldIE && $.mobile.browser.oldIE >= 7 ) && ( $.support.boundingRect || $.fn.jquery.match(/1\.[0-7+]\.[0-9+]?/) !== null );
1793 $.mobile.ajaxBlacklist =
1794 // BlackBerry browsers, pre-webkit
1795 window.blackberry && !window.WebKitPoint ||
1798 // Symbian webkits pre 7.3
1801 // Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices
1802 // to render the stylesheets when they're referenced before this script, as we'd recommend doing.
1803 // This simply reappends the CSS in place, which for some reason makes it apply
1804 if ( nokiaLTE7_3 ) {
1806 $( "head link[rel='stylesheet']" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" );
1810 // For ruling out shadows via css
1811 if ( !$.support.boxShadow ) {
1812 $( "html" ).addClass( "ui-mobile-nosupport-boxshadow" );
1818 (function( $, undefined ) {
1819 var $win = $.mobile.window, self, history;
1821 $.event.special.navigate = self = {
1824 pushStateEnabled: true,
1826 originalEventName: undefined,
1828 // If pushstate support is present and push state support is defined to
1829 // be true on the mobile namespace.
1830 isPushStateEnabled: function() {
1831 return $.support.pushState &&
1832 $.mobile.pushStateEnabled === true &&
1833 this.isHashChangeEnabled();
1836 // !! assumes mobile namespace is present
1837 isHashChangeEnabled: function() {
1838 return $.mobile.hashListeningEnabled === true;
1841 // TODO a lot of duplication between popstate and hashchange
1842 popstate: function( event ) {
1843 var newEvent = new $.Event( "navigate" ),
1844 beforeNavigate = new $.Event( "beforenavigate" ),
1845 state = event.originalEvent.state || {},
1846 href = location.href;
1848 $win.trigger( beforeNavigate );
1850 if( beforeNavigate.isDefaultPrevented() ){
1854 if( event.historyState ){
1855 $.extend(state, event.historyState);
1858 // Make sure the original event is tracked for the end
1859 // user to inspect incase they want to do something special
1860 newEvent.originalEvent = event;
1862 // NOTE we let the current stack unwind because any assignment to
1863 // location.hash will stop the world and run this event handler. By
1864 // doing this we create a similar behavior to hashchange on hash
1866 setTimeout(function() {
1867 $win.trigger( newEvent, {
1873 hashchange: function( event, data ) {
1874 var newEvent = new $.Event( "navigate" ),
1875 beforeNavigate = new $.Event( "beforenavigate" );
1877 $win.trigger( beforeNavigate );
1879 if( beforeNavigate.isDefaultPrevented() ){
1883 // Make sure the original event is tracked for the end
1884 // user to inspect incase they want to do something special
1885 newEvent.originalEvent = event;
1887 // Trigger the hashchange with state provided by the user
1888 // that altered the hash
1889 $win.trigger( newEvent, {
1890 // Users that want to fully normalize the two events
1891 // will need to do history management down the stack and
1892 // add the state to the event before this binding is fired
1893 // TODO consider allowing for the explicit addition of callbacks
1894 // to be fired before this value is set to avoid event timing issues
1895 state: event.hashchangeState || {}
1899 // TODO We really only want to set this up once
1900 // but I'm not clear if there's a beter way to achieve
1901 // this with the jQuery special event structure
1902 setup: function( data, namespaces ) {
1909 if( self.isPushStateEnabled() ) {
1910 self.originalEventName = "popstate";
1911 $win.bind( "popstate.navigate", self.popstate );
1912 } else if ( self.isHashChangeEnabled() ){
1913 self.originalEventName = "hashchange";
1914 $win.bind( "hashchange.navigate", self.hashchange );
1922 (function( $, undefined ) {
1923 var path, documentBase, $base, dialogHashKey = "&ui-state=dialog";
1925 $.mobile.path = path = {
1926 uiStateKey: "&ui-state",
1928 // This scary looking regular expression parses an absolute URL or its relative
1929 // variants (protocol, site, document, query, and hash), into the various
1930 // components (protocol, host, path, query, fragment, etc that make up the
1931 // URL as well as some other commonly used sub-parts. When used with RegExp.exec()
1932 // or String.match, it parses the URL into a results array that looks like this:
1934 // [0]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread#msg-content
1935 // [1]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread
1936 // [2]: http://jblas:password@mycompany.com:8080/mail/inbox
1937 // [3]: http://jblas:password@mycompany.com:8080
1940 // [6]: jblas:password@mycompany.com:8080
1941 // [7]: jblas:password
1944 // [10]: mycompany.com:8080
1945 // [11]: mycompany.com
1947 // [13]: /mail/inbox
1950 // [16]: ?msg=1234&type=unread
1951 // [17]: #msg-content
1953 urlParseRE: /^\s*(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,
1955 // Abstraction to address xss (Issue #4787) by removing the authority in
1956 // browsers that auto decode it. All references to location.href should be
1957 // replaced with a call to this method so that it can be dealt with properly here
1958 getLocation: function( url ) {
1959 var uri = url ? this.parseUrl( url ) : location,
1960 hash = this.parseUrl( url || location.href ).hash;
1962 // mimic the browser with an empty string when the hash is empty
1963 hash = hash === "#" ? "" : hash;
1965 // Make sure to parse the url or the location object for the hash because using location.hash
1966 // is autodecoded in firefox, the rest of the url should be from the object (location unless
1967 // we're testing) to avoid the inclusion of the authority
1968 return uri.protocol + "//" + uri.host + uri.pathname + uri.search + hash;
1971 parseLocation: function() {
1972 return this.parseUrl( this.getLocation() );
1975 //Parse a URL into a structure that allows easy access to
1976 //all of the URL components by name.
1977 parseUrl: function( url ) {
1978 // If we're passed an object, we'll assume that it is
1979 // a parsed url object and just return it back to the caller.
1980 if ( $.type( url ) === "object" ) {
1984 var matches = path.urlParseRE.exec( url || "" ) || [];
1986 // Create an object that allows the caller to access the sub-matches
1987 // by name. Note that IE returns an empty string instead of undefined,
1988 // like all other browsers do, so we normalize everything so its consistent
1989 // no matter what browser we're running on.
1991 href: matches[ 0 ] || "",
1992 hrefNoHash: matches[ 1 ] || "",
1993 hrefNoSearch: matches[ 2 ] || "",
1994 domain: matches[ 3 ] || "",
1995 protocol: matches[ 4 ] || "",
1996 doubleSlash: matches[ 5 ] || "",
1997 authority: matches[ 6 ] || "",
1998 username: matches[ 8 ] || "",
1999 password: matches[ 9 ] || "",
2000 host: matches[ 10 ] || "",
2001 hostname: matches[ 11 ] || "",
2002 port: matches[ 12 ] || "",
2003 pathname: matches[ 13 ] || "",
2004 directory: matches[ 14 ] || "",
2005 filename: matches[ 15 ] || "",
2006 search: matches[ 16 ] || "",
2007 hash: matches[ 17 ] || ""
2011 //Turn relPath into an asbolute path. absPath is
2012 //an optional absolute path which describes what
2013 //relPath is relative to.
2014 makePathAbsolute: function( relPath, absPath ) {
2015 if ( relPath && relPath.charAt( 0 ) === "/" ) {
2019 relPath = relPath || "";
2020 absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : "";
2022 var absStack = absPath ? absPath.split( "/" ) : [],
2023 relStack = relPath.split( "/" );
2024 for ( var i = 0; i < relStack.length; i++ ) {
2025 var d = relStack[ i ];
2030 if ( absStack.length ) {
2039 return "/" + absStack.join( "/" );
2042 //Returns true if both urls have the same domain.
2043 isSameDomain: function( absUrl1, absUrl2 ) {
2044 return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain;
2047 //Returns true for any relative variant.
2048 isRelativeUrl: function( url ) {
2049 // All relative Url variants have one thing in common, no protocol.
2050 return path.parseUrl( url ).protocol === "";
2053 //Returns true for an absolute url.
2054 isAbsoluteUrl: function( url ) {
2055 return path.parseUrl( url ).protocol !== "";
2058 //Turn the specified realtive URL into an absolute one. This function
2059 //can handle all relative variants (protocol, site, document, query, fragment).
2060 makeUrlAbsolute: function( relUrl, absUrl ) {
2061 if ( !path.isRelativeUrl( relUrl ) ) {
2065 if ( absUrl === undefined ) {
2066 absUrl = this.documentBase;
2069 var relObj = path.parseUrl( relUrl ),
2070 absObj = path.parseUrl( absUrl ),
2071 protocol = relObj.protocol || absObj.protocol,
2072 doubleSlash = relObj.protocol ? relObj.doubleSlash : ( relObj.doubleSlash || absObj.doubleSlash ),
2073 authority = relObj.authority || absObj.authority,
2074 hasPath = relObj.pathname !== "",
2075 pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ),
2076 search = relObj.search || ( !hasPath && absObj.search ) || "",
2079 return protocol + doubleSlash + authority + pathname + search + hash;
2082 //Add search (aka query) params to the specified url.
2083 addSearchParams: function( url, params ) {
2084 var u = path.parseUrl( url ),
2085 p = ( typeof params === "object" ) ? $.param( params ) : params,
2086 s = u.search || "?";
2087 return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" );
2090 convertUrlToDataUrl: function( absUrl ) {
2091 var u = path.parseUrl( absUrl );
2092 if ( path.isEmbeddedPage( u ) ) {
2093 // For embedded pages, remove the dialog hash key as in getFilePath(),
2094 // and remove otherwise the Data Url won't match the id of the embedded Page.
2096 .split( dialogHashKey )[0]
2097 .replace( /^#/, "" )
2098 .replace( /\?.*$/, "" );
2099 } else if ( path.isSameDomain( u, this.documentBase ) ) {
2100 return u.hrefNoHash.replace( this.documentBase.domain, "" ).split( dialogHashKey )[0];
2103 return window.decodeURIComponent(absUrl);
2106 //get path from current hash, or from a file path
2107 get: function( newPath ) {
2108 if ( newPath === undefined ) {
2109 newPath = path.parseLocation().hash;
2111 return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, '' );
2114 //set location hash to path
2115 set: function( path ) {
2116 location.hash = path;
2119 //test if a given url (string) is a path
2120 //NOTE might be exceptionally naive
2121 isPath: function( url ) {
2122 return ( /\// ).test( url );
2125 //return a url path with the window's location protocol/hostname/pathname removed
2126 clean: function( url ) {
2127 return url.replace( this.documentBase.domain, "" );
2130 //just return the url without an initial #
2131 stripHash: function( url ) {
2132 return url.replace( /^#/, "" );
2135 stripQueryParams: function( url ) {
2136 return url.replace( /\?.*$/, "" );
2139 //remove the preceding hash, any query params, and dialog notations
2140 cleanHash: function( hash ) {
2141 return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) );
2144 isHashValid: function( hash ) {
2145 return ( /^#[^#]+$/ ).test( hash );
2148 //check whether a url is referencing the same domain, or an external domain or different protocol
2149 //could be mailto, etc
2150 isExternal: function( url ) {
2151 var u = path.parseUrl( url );
2152 return u.protocol && u.domain !== this.documentUrl.domain ? true : false;
2155 hasProtocol: function( url ) {
2156 return ( /^(:?\w+:)/ ).test( url );
2159 isEmbeddedPage: function( url ) {
2160 var u = path.parseUrl( url );
2162 //if the path is absolute, then we need to compare the url against
2163 //both the this.documentUrl and the documentBase. The main reason for this
2164 //is that links embedded within external documents will refer to the
2165 //application document, whereas links embedded within the application
2166 //document will be resolved against the document base.
2167 if ( u.protocol !== "" ) {
2168 return ( !this.isPath(u.hash) && u.hash && ( u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ) ) );
2170 return ( /^#/ ).test( u.href );
2173 squash: function( url, resolutionUrl ) {
2174 var state, href, cleanedUrl, search, stateIndex,
2175 isPath = this.isPath( url ),
2176 uri = this.parseUrl( url ),
2177 preservedHash = uri.hash,
2180 // produce a url against which we can resole the provided path
2181 resolutionUrl = resolutionUrl || (path.isPath(url) ? path.getLocation() : path.getDocumentUrl());
2183 // If the url is anything but a simple string, remove any preceding hash
2184 // eg #foo/bar -> foo/bar
2186 cleanedUrl = isPath ? path.stripHash( url ) : url;
2188 // If the url is a full url with a hash check if the parsed hash is a path
2189 // if it is, strip the #, and use it otherwise continue without change
2190 cleanedUrl = path.isPath( uri.hash ) ? path.stripHash( uri.hash ) : cleanedUrl;
2192 // Split the UI State keys off the href
2193 stateIndex = cleanedUrl.indexOf( this.uiStateKey );
2195 // store the ui state keys for use
2196 if( stateIndex > -1 ){
2197 uiState = cleanedUrl.slice( stateIndex );
2198 cleanedUrl = cleanedUrl.slice( 0, stateIndex );
2201 // make the cleanedUrl absolute relative to the resolution url
2202 href = path.makeUrlAbsolute( cleanedUrl, resolutionUrl );
2204 // grab the search from the resolved url since parsing from
2205 // the passed url may not yield the correct result
2206 search = this.parseUrl( href ).search;
2208 // TODO all this crap is terrible, clean it up
2210 // reject the hash if it's a path or it's just a dialog key
2211 if( path.isPath( preservedHash ) || preservedHash.replace("#", "").indexOf( this.uiStateKey ) === 0) {
2215 // Append the UI State keys where it exists and it's been removed
2217 if( uiState && preservedHash.indexOf( this.uiStateKey ) === -1){
2218 preservedHash += uiState;
2221 // make sure that pound is on the front of the hash
2222 if( preservedHash.indexOf( "#" ) === -1 && preservedHash !== "" ){
2223 preservedHash = "#" + preservedHash;
2226 // reconstruct each of the pieces with the new search string and hash
2227 href = path.parseUrl( href );
2228 href = href.protocol + "//" + href.host + href.pathname + search + preservedHash;
2230 href += href.indexOf( "#" ) > -1 ? uiState : "#" + uiState;
2236 isPreservableHash: function( hash ) {
2237 return hash.replace( "#", "" ).indexOf( this.uiStateKey ) === 0;
2241 path.documentUrl = path.parseLocation();
2243 $base = $( "head" ).find( "base" );
2245 path.documentBase = $base.length ?
2246 path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), path.documentUrl.href ) ) :
2249 path.documentBaseDiffers = (path.documentUrl.hrefNoHash !== path.documentBase.hrefNoHash);
2251 //return the original document url
2252 path.getDocumentUrl = function( asParsedObject ) {
2253 return asParsedObject ? $.extend( {}, path.documentUrl ) : path.documentUrl.href;
2256 //return the original document base url
2257 path.getDocumentBase = function( asParsedObject ) {
2258 return asParsedObject ? $.extend( {}, path.documentBase ) : path.documentBase.href;
2264 (function( $, undefined ) {
2265 var path = $.mobile.path;
2267 $.mobile.History = function( stack, index ) {
2268 this.stack = stack || [];
2269 this.activeIndex = index || 0;
2272 $.extend($.mobile.History.prototype, {
2273 getActive: function() {
2274 return this.stack[ this.activeIndex ];
2277 getLast: function() {
2278 return this.stack[ this.previousIndex ];
2281 getNext: function() {
2282 return this.stack[ this.activeIndex + 1 ];
2285 getPrev: function() {
2286 return this.stack[ this.activeIndex - 1 ];
2289 // addNew is used whenever a new page is added
2290 add: function( url, data ){
2293 //if there's forward history, wipe it
2294 if ( this.getNext() ) {
2295 this.clearForward();
2298 // if the hash is included in the data make sure the shape
2299 // is consistent for comparison
2300 if( data.hash && data.hash.indexOf( "#" ) === -1) {
2301 data.hash = "#" + data.hash;
2305 this.stack.push( data );
2306 this.activeIndex = this.stack.length - 1;
2309 //wipe urls ahead of active index
2310 clearForward: function() {
2311 this.stack = this.stack.slice( 0, this.activeIndex + 1 );
2314 find: function( url, stack, earlyReturn ) {
2315 stack = stack || this.stack;
2317 var entry, i, length = stack.length, index;
2319 for ( i = 0; i < length; i++ ) {
2322 if ( decodeURIComponent(url) === decodeURIComponent(entry.url) ||
2323 decodeURIComponent(url) === decodeURIComponent(entry.hash) ) {
2335 closest: function( url ) {
2336 var closest, a = this.activeIndex;
2338 // First, take the slice of the history stack before the current index and search
2339 // for a url match. If one is found, we'll avoid avoid looking through forward history
2340 // NOTE the preference for backward history movement is driven by the fact that
2341 // most mobile browsers only have a dedicated back button, and users rarely use
2342 // the forward button in desktop browser anyhow
2343 closest = this.find( url, this.stack.slice(0, a) );
2345 // If nothing was found in backward history check forward. The `true`
2346 // value passed as the third parameter causes the find method to break
2347 // on the first match in the forward history slice. The starting index
2348 // of the slice must then be added to the result to get the element index
2349 // in the original history stack :( :(
2351 // TODO this is hyper confusing and should be cleaned up (ugh so bad)
2352 if( closest === undefined ) {
2353 closest = this.find( url, this.stack.slice(a), true );
2354 closest = closest === undefined ? closest : closest + a;
2360 direct: function( opts ) {
2361 var newActiveIndex = this.closest( opts.url ), a = this.activeIndex;
2363 // save new page index, null check to prevent falsey 0 result
2364 // record the previous index for reference
2365 if( newActiveIndex !== undefined ) {
2366 this.activeIndex = newActiveIndex;
2367 this.previousIndex = a;
2370 // invoke callbacks where appropriate
2372 // TODO this is also convoluted and confusing
2373 if ( newActiveIndex < a ) {
2374 ( opts.present || opts.back || $.noop )( this.getActive(), 'back' );
2375 } else if ( newActiveIndex > a ) {
2376 ( opts.present || opts.forward || $.noop )( this.getActive(), 'forward' );
2377 } else if ( newActiveIndex === undefined && opts.missing ){
2378 opts.missing( this.getActive() );
2385 (function( $, undefined ) {
2386 var path = $.mobile.path,
2387 initialHref = location.href;
2389 $.mobile.Navigator = function( history ) {
2390 this.history = history;
2391 this.ignoreInitialHashChange = true;
2393 $.mobile.window.bind({
2394 "popstate.history": $.proxy( this.popstate, this ),
2395 "hashchange.history": $.proxy( this.hashchange, this )
2399 $.extend($.mobile.Navigator.prototype, {
2400 squash: function( url, data ) {
2401 var state, href, hash = path.isPath(url) ? path.stripHash(url) : url;
2403 href = path.squash( url );
2405 // make sure to provide this information when it isn't explicitly set in the
2406 // data object that was passed to the squash method
2412 // replace the current url with the new href and store the state
2413 // Note that in some cases we might be replacing an url with the
2414 // same url. We do this anyways because we need to make sure that
2415 // all of our history entries have a state object associated with
2416 // them. This allows us to work around the case where $.mobile.back()
2417 // is called to transition from an external page to an embedded page.
2418 // In that particular case, a hashchange event is *NOT* generated by the browser.
2419 // Ensuring each history entry has a state object means that onPopState()
2420 // will always trigger our hashchange callback even when a hashchange event
2422 window.history.replaceState( state, state.title || document.title, href );
2427 hash: function( url, href ) {
2428 var parsed, loc, hash;
2430 // Grab the hash for recording. If the passed url is a path
2431 // we used the parsed version of the squashed url to reconstruct,
2432 // otherwise we assume it's a hash and store it directly
2433 parsed = path.parseUrl( url );
2434 loc = path.parseLocation();
2436 if( loc.pathname + loc.search === parsed.pathname + parsed.search ) {
2437 // If the pathname and search of the passed url is identical to the current loc
2438 // then we must use the hash. Otherwise there will be no event
2439 // eg, url = "/foo/bar?baz#bang", location.href = "http://example.com/foo/bar?baz"
2440 hash = parsed.hash ? parsed.hash : parsed.pathname + parsed.search;
2441 } else if ( path.isPath(url) ) {
2442 var resolved = path.parseUrl( href );
2443 // If the passed url is a path, make it domain relative and remove any trailing hash
2444 hash = resolved.pathname + resolved.search + (path.isPreservableHash( resolved.hash )? resolved.hash.replace( "#", "" ) : "");
2452 // TODO reconsider name
2453 go: function( url, data, noEvents ) {
2454 var state, href, hash, popstateEvent,
2455 isPopStateEvent = $.event.special.navigate.isPushStateEnabled();
2457 // Get the url as it would look squashed on to the current resolution url
2458 href = path.squash( url );
2460 // sort out what the hash sould be from the url
2461 hash = this.hash( url, href );
2463 // Here we prevent the next hash change or popstate event from doing any
2464 // history management. In the case of hashchange we don't swallow it
2465 // if there will be no hashchange fired (since that won't reset the value)
2466 // and will swallow the following hashchange
2467 if( noEvents && hash !== path.stripHash(path.parseLocation().hash) ) {
2468 this.preventNextHashChange = noEvents;
2471 // IMPORTANT in the case where popstate is supported the event will be triggered
2472 // directly, stopping further execution - ie, interupting the flow of this
2473 // method call to fire bindings at this expression. Below the navigate method
2474 // there is a binding to catch this event and stop its propagation.
2476 // We then trigger a new popstate event on the window with a null state
2477 // so that the navigate events can conclude their work properly
2479 // if the url is a path we want to preserve the query params that are available on
2481 this.preventHashAssignPopState = true;
2482 window.location.hash = hash;
2484 // If popstate is enabled and the browser triggers `popstate` events when the hash
2485 // is set (this often happens immediately in browsers like Chrome), then the
2486 // this flag will be set to false already. If it's a browser that does not trigger
2487 // a `popstate` on hash assignement or `replaceState` then we need avoid the branch
2488 // that swallows the event created by the popstate generated by the hash assignment
2489 // At the time of this writing this happens with Opera 12 and some version of IE
2490 this.preventHashAssignPopState = false;
2495 title: document.title
2498 if( isPopStateEvent ) {
2499 popstateEvent = new $.Event( "popstate" );
2500 popstateEvent.originalEvent = {
2505 this.squash( url, state );
2507 // Trigger a new faux popstate event to replace the one that we
2508 // caught that was triggered by the hash setting above.
2510 this.ignorePopState = true;
2511 $.mobile.window.trigger( popstateEvent );
2515 // record the history entry so that the information can be included
2516 // in hashchange event driven navigate events in a similar fashion to
2517 // the state that's provided by popstate
2518 this.history.add( state.url, state );
2522 // This binding is intended to catch the popstate events that are fired
2523 // when execution of the `$.navigate` method stops at window.location.hash = url;
2524 // and completely prevent them from propagating. The popstate event will then be
2525 // retriggered after execution resumes
2527 // TODO grab the original event here and use it for the synthetic event in the
2528 // second half of the navigate execution that will follow this binding
2529 popstate: function( event ) {
2530 var active, hash, state, closestIndex;
2532 // Partly to support our test suite which manually alters the support
2533 // value to test hashchange. Partly to prevent all around weirdness
2534 if( !$.event.special.navigate.isPushStateEnabled() ){
2538 // If this is the popstate triggered by the actual alteration of the hash
2539 // prevent it completely. History is tracked manually
2540 if( this.preventHashAssignPopState ) {
2541 this.preventHashAssignPopState = false;
2542 event.stopImmediatePropagation();
2546 // if this is the popstate triggered after the `replaceState` call in the go
2547 // method, then simply ignore it. The history entry has already been captured
2548 if( this.ignorePopState ) {
2549 this.ignorePopState = false;
2553 // If there is no state, and the history stack length is one were
2554 // probably getting the page load popstate fired by browsers like chrome
2555 // avoid it and set the one time flag to false.
2556 // TODO: Do we really need all these conditions? Comparing location hrefs
2557 // should be sufficient.
2558 if( !event.originalEvent.state &&
2559 this.history.stack.length === 1 &&
2560 this.ignoreInitialHashChange ) {
2561 this.ignoreInitialHashChange = false;
2563 if ( location.href === initialHref ) {
2564 event.preventDefault();
2569 // account for direct manipulation of the hash. That is, we will receive a popstate
2570 // when the hash is changed by assignment, and it won't have a state associated. We
2571 // then need to squash the hash. See below for handling of hash assignment that
2572 // matches an existing history entry
2573 // TODO it might be better to only add to the history stack
2574 // when the hash is adjacent to the active history entry
2575 hash = path.parseLocation().hash;
2576 if( !event.originalEvent.state && hash ) {
2577 // squash the hash that's been assigned on the URL with replaceState
2578 // also grab the resulting state object for storage
2579 state = this.squash( hash );
2581 // record the new hash as an additional history entry
2582 // to match the browser's treatment of hash assignment
2583 this.history.add( state.url, state );
2585 // pass the newly created state information
2586 // along with the event
2587 event.historyState = state;
2589 // do not alter history, we've added a new history entry
2590 // so we know where we are
2594 // If all else fails this is a popstate that comes from the back or forward buttons
2595 // make sure to set the state of our history stack properly, and record the directionality
2596 this.history.direct({
2597 url: (event.originalEvent.state || {}).url || hash,
2599 // When the url is either forward or backward in history include the entry
2600 // as data on the event object for merging as data in the navigate event
2601 present: function( historyEntry, direction ) {
2602 // make sure to create a new object to pass down as the navigate event data
2603 event.historyState = $.extend({}, historyEntry);
2604 event.historyState.direction = direction;
2609 // NOTE must bind before `navigate` special event hashchange binding otherwise the
2610 // navigation data won't be attached to the hashchange event in time for those
2611 // bindings to attach it to the `navigate` special event
2612 // TODO add a check here that `hashchange.navigate` is bound already otherwise it's
2613 // broken (exception?)
2614 hashchange: function( event ) {
2617 // If hashchange listening is explicitly disabled or pushstate is supported
2618 // avoid making use of the hashchange handler.
2619 if(!$.event.special.navigate.isHashChangeEnabled() ||
2620 $.event.special.navigate.isPushStateEnabled() ) {
2624 // On occasion explicitly want to prevent the next hash from propogating because we only
2625 // with to alter the url to represent the new state do so here
2626 if( this.preventNextHashChange ){
2627 this.preventNextHashChange = false;
2628 event.stopImmediatePropagation();
2632 history = this.history;
2633 hash = path.parseLocation().hash;
2635 // If this is a hashchange caused by the back or forward button
2636 // make sure to set the state of our history stack properly
2637 this.history.direct({
2640 // When the url is either forward or backward in history include the entry
2641 // as data on the event object for merging as data in the navigate event
2642 present: function( historyEntry, direction ) {
2643 // make sure to create a new object to pass down as the navigate event data
2644 event.hashchangeState = $.extend({}, historyEntry);
2645 event.hashchangeState.direction = direction;
2648 // When we don't find a hash in our history clearly we're aiming to go there
2649 // record the entry as new for future traversal
2651 // NOTE it's not entirely clear that this is the right thing to do given that we
2652 // can't know the users intention. It might be better to explicitly _not_
2653 // support location.hash assignment in preference to $.navigate calls
2654 // TODO first arg to add should be the href, but it causes issues in identifying
2656 missing: function() {
2657 history.add( hash, {
2659 title: document.title
2669 (function( $, undefined ) {
2670 // TODO consider queueing navigation activity until previous activities have completed
2671 // so that end users don't have to think about it. Punting for now
2672 // TODO !! move the event bindings into callbacks on the navigate event
2673 $.mobile.navigate = function( url, data, noEvents ) {
2674 $.mobile.navigate.navigator.go( url, data, noEvents );
2677 // expose the history on the navigate method in anticipation of full integration with
2678 // existing navigation functionalty that is tightly coupled to the history information
2679 $.mobile.navigate.history = new $.mobile.History();
2681 // instantiate an instance of the navigator for use within the $.navigate method
2682 $.mobile.navigate.navigator = new $.mobile.Navigator( $.mobile.navigate.history );
2684 var loc = $.mobile.path.parseLocation();
2685 $.mobile.navigate.history.add( loc.href, {hash: loc.hash} );
2689 // This plugin is an experiment for abstracting away the touch and mouse
2690 // events so that developers don't have to worry about which method of input
2691 // the device their document is loaded on supports.
2693 // The idea here is to allow the developer to register listeners for the
2694 // basic mouse events, such as mousedown, mousemove, mouseup, and click,
2695 // and the plugin will take care of registering the correct listeners
2696 // behind the scenes to invoke the listener at the fastest possible time
2697 // for that device, while still retaining the order of event firing in
2698 // the traditional mouse environment, should multiple handlers be registered
2699 // on the same element for different events.
2701 // The current version exposes the following virtual events to jQuery bind methods:
2702 // "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel"
2704 (function( $, window, document, undefined ) {
2706 var dataPropertyName = "virtualMouseBindings",
2707 touchTargetPropertyName = "virtualTouchID",
2708 virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ),
2709 touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ),
2710 mouseHookProps = $.event.mouseHooks ? $.event.mouseHooks.props : [],
2711 mouseEventProps = $.event.props.concat( mouseHookProps ),
2712 activeDocHandlers = {},
2717 clickBlockList = [],
2718 blockMouseTriggers = false,
2719 blockTouchTriggers = false,
2720 eventCaptureSupported = "addEventListener" in document,
2721 $document = $( document ),
2723 lastTouchID = 0, threshold;
2726 moveDistanceThreshold: 10,
2727 clickDistanceThreshold: 10,
2728 resetTimerDuration: 1500
2731 function getNativeEvent( event ) {
2733 while ( event && typeof event.originalEvent !== "undefined" ) {
2734 event = event.originalEvent;
2739 function createVirtualEvent( event, eventType ) {
2742 oe, props, ne, prop, ct, touch, i, j, len;
2744 event = $.Event( event );
2745 event.type = eventType;
2747 oe = event.originalEvent;
2748 props = $.event.props;
2750 // addresses separation of $.event.props in to $.event.mouseHook.props and Issue 3280
2751 // https://github.com/jquery/jquery-mobile/issues/3280
2752 if ( t.search( /^(mouse|click)/ ) > -1 ) {
2753 props = mouseEventProps;
2756 // copy original event properties over to the new event
2757 // this would happen if we could call $.event.fix instead of $.Event
2758 // but we don't have a way to force an event to be fixed multiple times
2760 for ( i = props.length, prop; i; ) {
2761 prop = props[ --i ];
2762 event[ prop ] = oe[ prop ];
2766 // make sure that if the mouse and click virtual events are generated
2767 // without a .which one is defined
2768 if ( t.search(/mouse(down|up)|click/) > -1 && !event.which ) {
2772 if ( t.search(/^touch/) !== -1 ) {
2773 ne = getNativeEvent( oe );
2775 ct = ne.changedTouches;
2776 touch = ( t && t.length ) ? t[0] : ( ( ct && ct.length ) ? ct[ 0 ] : undefined );
2779 for ( j = 0, len = touchEventProps.length; j < len; j++) {
2780 prop = touchEventProps[ j ];
2781 event[ prop ] = touch[ prop ];
2789 function getVirtualBindingFlags( element ) {
2796 b = $.data( element, dataPropertyName );
2800 flags[ k ] = flags.hasVirtualBinding = true;
2803 element = element.parentNode;
2808 function getClosestElementWithVirtualBinding( element, eventType ) {
2812 b = $.data( element, dataPropertyName );
2814 if ( b && ( !eventType || b[ eventType ] ) ) {
2817 element = element.parentNode;
2822 function enableTouchBindings() {
2823 blockTouchTriggers = false;
2826 function disableTouchBindings() {
2827 blockTouchTriggers = true;
2830 function enableMouseBindings() {
2832 clickBlockList.length = 0;
2833 blockMouseTriggers = false;
2835 // When mouse bindings are enabled, our
2836 // touch bindings are disabled.
2837 disableTouchBindings();
2840 function disableMouseBindings() {
2841 // When mouse bindings are disabled, our
2842 // touch bindings are enabled.
2843 enableTouchBindings();
2846 function startResetTimer() {
2848 resetTimerID = setTimeout( function() {
2850 enableMouseBindings();
2851 }, $.vmouse.resetTimerDuration );
2854 function clearResetTimer() {
2855 if ( resetTimerID ) {
2856 clearTimeout( resetTimerID );
2861 function triggerVirtualEvent( eventType, event, flags ) {
2864 if ( ( flags && flags[ eventType ] ) ||
2865 ( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) {
2867 ve = createVirtualEvent( event, eventType );
2869 $( event.target).trigger( ve );
2875 function mouseEventCallback( event ) {
2876 var touchID = $.data( event.target, touchTargetPropertyName );
2878 if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ) {
2879 var ve = triggerVirtualEvent( "v" + event.type, event );
2881 if ( ve.isDefaultPrevented() ) {
2882 event.preventDefault();
2884 if ( ve.isPropagationStopped() ) {
2885 event.stopPropagation();
2887 if ( ve.isImmediatePropagationStopped() ) {
2888 event.stopImmediatePropagation();
2894 function handleTouchStart( event ) {
2896 var touches = getNativeEvent( event ).touches,
2899 if ( touches && touches.length === 1 ) {
2901 target = event.target;
2902 flags = getVirtualBindingFlags( target );
2904 if ( flags.hasVirtualBinding ) {
2906 lastTouchID = nextTouchID++;
2907 $.data( target, touchTargetPropertyName, lastTouchID );
2911 disableMouseBindings();
2914 var t = getNativeEvent( event ).touches[ 0 ];
2918 triggerVirtualEvent( "vmouseover", event, flags );
2919 triggerVirtualEvent( "vmousedown", event, flags );
2924 function handleScroll( event ) {
2925 if ( blockTouchTriggers ) {
2930 triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) );
2937 function handleTouchMove( event ) {
2938 if ( blockTouchTriggers ) {
2942 var t = getNativeEvent( event ).touches[ 0 ],
2943 didCancel = didScroll,
2944 moveThreshold = $.vmouse.moveDistanceThreshold,
2945 flags = getVirtualBindingFlags( event.target );
2947 didScroll = didScroll ||
2948 ( Math.abs( t.pageX - startX ) > moveThreshold ||
2949 Math.abs( t.pageY - startY ) > moveThreshold );
2952 if ( didScroll && !didCancel ) {
2953 triggerVirtualEvent( "vmousecancel", event, flags );
2956 triggerVirtualEvent( "vmousemove", event, flags );
2960 function handleTouchEnd( event ) {
2961 if ( blockTouchTriggers ) {
2965 disableTouchBindings();
2967 var flags = getVirtualBindingFlags( event.target ),
2969 triggerVirtualEvent( "vmouseup", event, flags );
2972 var ve = triggerVirtualEvent( "vclick", event, flags );
2973 if ( ve && ve.isDefaultPrevented() ) {
2974 // The target of the mouse events that follow the touchend
2975 // event don't necessarily match the target used during the
2976 // touch. This means we need to rely on coordinates for blocking
2977 // any click that is generated.
2978 t = getNativeEvent( event ).changedTouches[ 0 ];
2979 clickBlockList.push({
2980 touchID: lastTouchID,
2985 // Prevent any mouse events that follow from triggering
2986 // virtual event notifications.
2987 blockMouseTriggers = true;
2990 triggerVirtualEvent( "vmouseout", event, flags);
2996 function hasVirtualBindings( ele ) {
2997 var bindings = $.data( ele, dataPropertyName ),
3001 for ( k in bindings ) {
3002 if ( bindings[ k ] ) {
3010 function dummyMouseHandler() {}
3012 function getSpecialEventObject( eventType ) {
3013 var realType = eventType.substr( 1 );
3016 setup: function( data, namespace ) {
3017 // If this is the first virtual mouse binding for this element,
3018 // add a bindings object to its data.
3020 if ( !hasVirtualBindings( this ) ) {
3021 $.data( this, dataPropertyName, {} );
3024 // If setup is called, we know it is the first binding for this
3025 // eventType, so initialize the count for the eventType to zero.
3026 var bindings = $.data( this, dataPropertyName );
3027 bindings[ eventType ] = true;
3029 // If this is the first virtual mouse event for this type,
3030 // register a global handler on the document.
3032 activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1;
3034 if ( activeDocHandlers[ eventType ] === 1 ) {
3035 $document.bind( realType, mouseEventCallback );
3038 // Some browsers, like Opera Mini, won't dispatch mouse/click events
3039 // for elements unless they actually have handlers registered on them.
3040 // To get around this, we register dummy handlers on the elements.
3042 $( this ).bind( realType, dummyMouseHandler );
3044 // For now, if event capture is not supported, we rely on mouse handlers.
3045 if ( eventCaptureSupported ) {
3046 // If this is the first virtual mouse binding for the document,
3047 // register our touchstart handler on the document.
3049 activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1;
3051 if ( activeDocHandlers[ "touchstart" ] === 1 ) {
3052 $document.bind( "touchstart", handleTouchStart )
3053 .bind( "touchend", handleTouchEnd )
3055 // On touch platforms, touching the screen and then dragging your finger
3056 // causes the window content to scroll after some distance threshold is
3057 // exceeded. On these platforms, a scroll prevents a click event from being
3058 // dispatched, and on some platforms, even the touchend is suppressed. To
3059 // mimic the suppression of the click event, we need to watch for a scroll
3060 // event. Unfortunately, some platforms like iOS don't dispatch scroll
3061 // events until *AFTER* the user lifts their finger (touchend). This means
3062 // we need to watch both scroll and touchmove events to figure out whether
3063 // or not a scroll happenens before the touchend event is fired.
3065 .bind( "touchmove", handleTouchMove )
3066 .bind( "scroll", handleScroll );
3071 teardown: function( data, namespace ) {
3072 // If this is the last virtual binding for this eventType,
3073 // remove its global handler from the document.
3075 --activeDocHandlers[ eventType ];
3077 if ( !activeDocHandlers[ eventType ] ) {
3078 $document.unbind( realType, mouseEventCallback );
3081 if ( eventCaptureSupported ) {
3082 // If this is the last virtual mouse binding in existence,
3083 // remove our document touchstart listener.
3085 --activeDocHandlers[ "touchstart" ];
3087 if ( !activeDocHandlers[ "touchstart" ] ) {
3088 $document.unbind( "touchstart", handleTouchStart )
3089 .unbind( "touchmove", handleTouchMove )
3090 .unbind( "touchend", handleTouchEnd )
3091 .unbind( "scroll", handleScroll );
3095 var $this = $( this ),
3096 bindings = $.data( this, dataPropertyName );
3098 // teardown may be called when an element was
3099 // removed from the DOM. If this is the case,
3100 // jQuery core may have already stripped the element
3101 // of any data bindings so we need to check it before
3104 bindings[ eventType ] = false;
3107 // Unregister the dummy event handler.
3109 $this.unbind( realType, dummyMouseHandler );
3111 // If this is the last virtual mouse binding on the
3112 // element, remove the binding data from the element.
3114 if ( !hasVirtualBindings( this ) ) {
3115 $this.removeData( dataPropertyName );
3121 // Expose our custom events to the jQuery bind/unbind mechanism.
3123 for ( var i = 0; i < virtualEventNames.length; i++ ) {
3124 $.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] );
3127 // Add a capture click handler to block clicks.
3128 // Note that we require event capture support for this so if the device
3129 // doesn't support it, we punt for now and rely solely on mouse events.
3130 if ( eventCaptureSupported ) {
3131 document.addEventListener( "click", function( e ) {
3132 var cnt = clickBlockList.length,
3134 x, y, ele, i, o, touchID;
3139 threshold = $.vmouse.clickDistanceThreshold;
3141 // The idea here is to run through the clickBlockList to see if
3142 // the current click event is in the proximity of one of our
3143 // vclick events that had preventDefault() called on it. If we find
3144 // one, then we block the click.
3146 // Why do we have to rely on proximity?
3148 // Because the target of the touch event that triggered the vclick
3149 // can be different from the target of the click event synthesized
3150 // by the browser. The target of a mouse/click event that is syntehsized
3151 // from a touch event seems to be implementation specific. For example,
3152 // some browsers will fire mouse/click events for a link that is near
3153 // a touch event, even though the target of the touchstart/touchend event
3154 // says the user touched outside the link. Also, it seems that with most
3155 // browsers, the target of the mouse/click event is not calculated until the
3156 // time it is dispatched, so if you replace an element that you touched
3157 // with another element, the target of the mouse/click will be the new
3158 // element underneath that point.
3160 // Aside from proximity, we also check to see if the target and any
3161 // of its ancestors were the ones that blocked a click. This is necessary
3162 // because of the strange mouse/click target calculation done in the
3163 // Android 2.1 browser, where if you click on an element, and there is a
3164 // mouse/click handler on one of its ancestors, the target will be the
3165 // innermost child of the touched element, even if that child is no where
3166 // near the point of touch.
3171 for ( i = 0; i < cnt; i++ ) {
3172 o = clickBlockList[ i ];
3175 if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) ||
3176 $.data( ele, touchTargetPropertyName ) === o.touchID ) {
3177 // XXX: We may want to consider removing matches from the block list
3178 // instead of waiting for the reset timer to fire.
3180 e.stopPropagation();
3184 ele = ele.parentNode;
3189 })( jQuery, window, document );
3192 (function( $, window, undefined ) {
3193 var $document = $( document );
3195 // add new event shortcuts
3196 $.each( ( "touchstart touchmove touchend " +
3198 "swipe swipeleft swiperight " +
3199 "scrollstart scrollstop" ).split( " " ), function( i, name ) {
3201 $.fn[ name ] = function( fn ) {
3202 return fn ? this.bind( name, fn ) : this.trigger( name );
3207 $.attrFn[ name ] = true;
3211 var supportTouch = $.mobile.support.touch,
3212 scrollEvent = "touchmove scroll",
3213 touchStartEvent = supportTouch ? "touchstart" : "mousedown",
3214 touchStopEvent = supportTouch ? "touchend" : "mouseup",
3215 touchMoveEvent = supportTouch ? "touchmove" : "mousemove";
3217 function triggerCustomEvent( obj, eventType, event ) {
3218 var originalType = event.type;
3219 event.type = eventType;
3220 $.event.dispatch.call( obj, event );
3221 event.type = originalType;
3224 // also handles scrollstop
3225 $.event.special.scrollstart = {
3231 var thisObject = this,
3232 $this = $( thisObject ),
3236 function trigger( event, state ) {
3238 triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event );
3241 // iPhone triggers scroll after a small delay; use touchmove instead
3242 $this.bind( scrollEvent, function( event ) {
3244 if ( !$.event.special.scrollstart.enabled ) {
3249 trigger( event, true );
3252 clearTimeout( timer );
3253 timer = setTimeout( function() {
3254 trigger( event, false );
3260 // also handles taphold
3261 $.event.special.tap = {
3262 tapholdThreshold: 750,
3265 var thisObject = this,
3266 $this = $( thisObject );
3268 $this.bind( "vmousedown", function( event ) {
3270 if ( event.which && event.which !== 1 ) {
3274 var origTarget = event.target,
3275 origEvent = event.originalEvent,
3278 function clearTapTimer() {
3279 clearTimeout( timer );
3282 function clearTapHandlers() {
3285 $this.unbind( "vclick", clickHandler )
3286 .unbind( "vmouseup", clearTapTimer );
3287 $document.unbind( "vmousecancel", clearTapHandlers );
3290 function clickHandler( event ) {
3293 // ONLY trigger a 'tap' event if the start target is
3294 // the same as the stop target.
3295 if ( origTarget === event.target ) {
3296 triggerCustomEvent( thisObject, "tap", event );
3300 $this.bind( "vmouseup", clearTapTimer )
3301 .bind( "vclick", clickHandler );
3302 $document.bind( "vmousecancel", clearTapHandlers );
3304 timer = setTimeout( function() {
3305 triggerCustomEvent( thisObject, "taphold", $.Event( "taphold", { target: origTarget } ) );
3306 }, $.event.special.tap.tapholdThreshold );
3311 // also handles swipeleft, swiperight
3312 $.event.special.swipe = {
3313 scrollSupressionThreshold: 30, // More than this horizontal displacement, and we will suppress scrolling.
3315 durationThreshold: 1000, // More time than this, and it isn't a swipe.
3317 horizontalDistanceThreshold: 30, // Swipe horizontal displacement must be more than this.
3319 verticalDistanceThreshold: 75, // Swipe vertical displacement must be less than this.
3321 start: function( event ) {
3322 var data = event.originalEvent.touches ?
3323 event.originalEvent.touches[ 0 ] : event;
3325 time: ( new Date() ).getTime(),
3326 coords: [ data.pageX, data.pageY ],
3327 origin: $( event.target )
3331 stop: function( event ) {
3332 var data = event.originalEvent.touches ?
3333 event.originalEvent.touches[ 0 ] : event;
3335 time: ( new Date() ).getTime(),
3336 coords: [ data.pageX, data.pageY ]
3340 handleSwipe: function( start, stop ) {
3341 if ( stop.time - start.time < $.event.special.swipe.durationThreshold &&
3342 Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold &&
3343 Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) {
3345 start.origin.trigger( "swipe" )
3346 .trigger( start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight" );
3351 var thisObject = this,
3352 $this = $( thisObject );
3354 $this.bind( touchStartEvent, function( event ) {
3355 var start = $.event.special.swipe.start( event ),
3358 function moveHandler( event ) {
3363 stop = $.event.special.swipe.stop( event );
3365 // prevent scrolling
3366 if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) {
3367 event.preventDefault();
3371 $this.bind( touchMoveEvent, moveHandler )
3372 .one( touchStopEvent, function() {
3373 $this.unbind( touchMoveEvent, moveHandler );
3375 if ( start && stop ) {
3376 $.event.special.swipe.handleSwipe( start, stop );
3378 start = stop = undefined;
3384 scrollstop: "scrollstart",
3388 }, function( event, sourceEvent ) {
3390 $.event.special[ event ] = {
3392 $( this ).bind( sourceEvent, $.noop );
3400 // throttled resize event
3402 $.event.special.throttledresize = {
3404 $( this ).bind( "resize", handler );
3406 teardown: function() {
3407 $( this ).unbind( "resize", handler );
3412 handler = function() {
3413 curr = ( new Date() ).getTime();
3414 diff = curr - lastCall;
3416 if ( diff >= throttle ) {
3419 $( this ).trigger( "throttledresize" );
3424 clearTimeout( heldCall );
3427 // Promise a held call will still execute
3428 heldCall = setTimeout( handler, throttle - diff );
3437 (function( $, window ) {
3438 var win = $( window ),
3439 event_name = "orientationchange",
3443 initial_orientation_is_landscape,
3444 initial_orientation_is_default,
3445 portrait_map = { "0": true, "180": true };
3447 // It seems that some device/browser vendors use window.orientation values 0 and 180 to
3448 // denote the "default" orientation. For iOS devices, and most other smart-phones tested,
3449 // the default orientation is always "portrait", but in some Android and RIM based tablets,
3450 // the default orientation is "landscape". The following code attempts to use the window
3451 // dimensions to figure out what the current orientation is, and then makes adjustments
3452 // to the to the portrait_map if necessary, so that we can properly decode the
3453 // window.orientation value whenever get_orientation() is called.
3455 // Note that we used to use a media query to figure out what the orientation the browser
3458 // initial_orientation_is_landscape = $.mobile.media("all and (orientation: landscape)");
3460 // but there was an iPhone/iPod Touch bug beginning with iOS 4.2, up through iOS 5.1,
3461 // where the browser *ALWAYS* applied the landscape media query. This bug does not
3464 if ( $.support.orientation ) {
3466 // Check the window width and height to figure out what the current orientation
3467 // of the device is at this moment. Note that we've initialized the portrait map
3468 // values to 0 and 180, *AND* we purposely check for landscape so that if we guess
3469 // wrong, , we default to the assumption that portrait is the default orientation.
3470 // We use a threshold check below because on some platforms like iOS, the iPhone
3471 // form-factor can report a larger width than height if the user turns on the
3472 // developer console. The actual threshold value is somewhat arbitrary, we just
3473 // need to make sure it is large enough to exclude the developer console case.
3475 var ww = window.innerWidth || win.width(),
3476 wh = window.innerHeight || win.height(),
3477 landscape_threshold = 50;
3479 initial_orientation_is_landscape = ww > wh && ( ww - wh ) > landscape_threshold;
3482 // Now check to see if the current window.orientation is 0 or 180.
3483 initial_orientation_is_default = portrait_map[ window.orientation ];
3485 // If the initial orientation is landscape, but window.orientation reports 0 or 180, *OR*
3486 // if the initial orientation is portrait, but window.orientation reports 90 or -90, we
3487 // need to flip our portrait_map values because landscape is the default orientation for
3488 // this device/browser.
3489 if ( ( initial_orientation_is_landscape && initial_orientation_is_default ) || ( !initial_orientation_is_landscape && !initial_orientation_is_default ) ) {
3490 portrait_map = { "-90": true, "90": true };
3494 $.event.special.orientationchange = $.extend( {}, $.event.special.orientationchange, {
3496 // If the event is supported natively, return false so that jQuery
3497 // will bind to the event using DOM methods.
3498 if ( $.support.orientation && !$.event.special.orientationchange.disabled ) {
3502 // Get the current orientation to avoid initial double-triggering.
3503 last_orientation = get_orientation();
3505 // Because the orientationchange event doesn't exist, simulate the
3506 // event by testing window dimensions on resize.
3507 win.bind( "throttledresize", handler );
3509 teardown: function() {
3510 // If the event is not supported natively, return false so that
3511 // jQuery will unbind the event using DOM methods.
3512 if ( $.support.orientation && !$.event.special.orientationchange.disabled ) {
3516 // Because the orientationchange event doesn't exist, unbind the
3517 // resize event handler.
3518 win.unbind( "throttledresize", handler );
3520 add: function( handleObj ) {
3521 // Save a reference to the bound event handler.
3522 var old_handler = handleObj.handler;
3525 handleObj.handler = function( event ) {
3526 // Modify event object, adding the .orientation property.
3527 event.orientation = get_orientation();
3529 // Call the originally-bound event handler and return its result.
3530 return old_handler.apply( this, arguments );
3535 // If the event is not supported natively, this handler will be bound to
3536 // the window resize event to simulate the orientationchange event.
3537 function handler() {
3538 // Get the current orientation.
3539 var orientation = get_orientation();
3541 if ( orientation !== last_orientation ) {
3542 // The orientation has changed, so trigger the orientationchange event.
3543 last_orientation = orientation;
3544 win.trigger( event_name );
3548 // Get the current page orientation. This method is exposed publicly, should it
3549 // be needed, as jQuery.event.special.orientationchange.orientation()
3550 $.event.special.orientationchange.orientation = get_orientation = function() {
3551 var isPortrait = true, elem = document.documentElement;
3553 // prefer window orientation to the calculation based on screensize as
3554 // the actual screen resize takes place before or after the orientation change event
3555 // has been fired depending on implementation (eg android 2.3 is before, iphone after).
3556 // More testing is required to determine if a more reliable method of determining the new screensize
3557 // is possible when orientationchange is fired. (eg, use media queries + element + opacity)
3558 if ( $.support.orientation ) {
3559 // if the window orientation registers as 0 or 180 degrees report
3560 // portrait, otherwise landscape
3561 isPortrait = portrait_map[ window.orientation ];
3563 isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1;
3566 return isPortrait ? "portrait" : "landscape";
3569 $.fn[ event_name ] = function( fn ) {
3570 return fn ? this.bind( event_name, fn ) : this.trigger( event_name );
3575 $.attrFn[ event_name ] = true;
3582 (function( $, undefined ) {
3584 $.widget( "mobile.page", $.mobile.widget, {
3588 keepNativeDefault: ":jqmData(role='none'), :jqmData(role='nojs')"
3591 _create: function() {
3592 // if false is returned by the callbacks do not create the page
3593 if ( this._trigger( "beforecreate" ) === false ) {
3598 .attr( "tabindex", "0" )
3599 .addClass( "ui-page ui-body-" + this.options.theme );
3601 this._on( this.element, {
3602 pagebeforehide: "removeContainerBackground",
3603 pagebeforeshow: "_handlePageBeforeShow"
3607 _handlePageBeforeShow: function( e ) {
3608 this.setContainerBackground();
3611 removeContainerBackground: function() {
3612 $.mobile.pageContainer.removeClass( "ui-overlay-" + $.mobile.getInheritedTheme( this.element.parent() ) );
3615 // set the page container background to the page theme
3616 setContainerBackground: function( theme ) {
3617 if ( this.options.theme ) {
3618 $.mobile.pageContainer.addClass( "ui-overlay-" + ( theme || this.options.theme ) );
3622 keepNativeSelector: function() {
3623 var options = this.options,
3624 keepNativeDefined = options.keepNative && $.trim( options.keepNative );
3626 if ( keepNativeDefined && options.keepNative !== options.keepNativeDefault ) {
3627 return [options.keepNative, options.keepNativeDefault].join( ", " );
3630 return options.keepNativeDefault;
3635 (function( $, window, undefined ) {
3637 var createHandler = function( sequential ) {
3639 // Default to sequential
3640 if ( sequential === undefined ) {
3644 return function( name, reverse, $to, $from ) {
3646 var deferred = new $.Deferred(),
3647 reverseClass = reverse ? " reverse" : "",
3648 active = $.mobile.urlHistory.getActive(),
3649 toScroll = active.lastScroll || $.mobile.defaultHomeScroll,
3650 screenHeight = $.mobile.getScreenHeight(),
3651 maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $.mobile.window.width() > $.mobile.maxTransitionWidth,
3652 none = !$.support.cssTransitions || maxTransitionOverride || !name || name === "none" || Math.max( $.mobile.window.scrollTop(), toScroll ) > $.mobile.getMaxScrollForTransition(),
3653 toPreClass = " ui-page-pre-in",
3654 toggleViewportClass = function() {
3655 $.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + name );
3657 scrollPage = function() {
3658 // By using scrollTo instead of silentScroll, we can keep things better in order
3659 // Just to be precautios, disable scrollstart listening like silentScroll would
3660 $.event.special.scrollstart.enabled = false;
3662 window.scrollTo( 0, toScroll );
3664 // reenable scrollstart listening like silentScroll would
3665 setTimeout( function() {
3666 $.event.special.scrollstart.enabled = true;
3669 cleanFrom = function() {
3671 .removeClass( $.mobile.activePageClass + " out in reverse " + name )
3674 startOut = function() {
3675 // if it's not sequential, call the doneOut transition to start the TO page animating in simultaneously
3676 if ( !sequential ) {
3680 $from.animationComplete( doneOut );
3683 // Set the from page's height and start it transitioning out
3684 // Note: setting an explicit height helps eliminate tiling in the transitions
3686 .height( screenHeight + $.mobile.window.scrollTop() )
3687 .addClass( name + " out" + reverseClass );
3690 doneOut = function() {
3692 if ( $from && sequential ) {
3699 startIn = function() {
3701 // Prevent flickering in phonegap container: see comments at #4024 regarding iOS
3702 $to.css( "z-index", -10 );
3704 $to.addClass( $.mobile.activePageClass + toPreClass );
3706 // Send focus to page as it is now display: block
3707 $.mobile.focusPage( $to );
3709 // Set to page height
3710 $to.height( screenHeight + toScroll );
3714 // Restores visibility of the new page: added together with $to.css( "z-index", -10 );
3715 $to.css( "z-index", "" );
3718 $to.animationComplete( doneIn );
3722 .removeClass( toPreClass )
3723 .addClass( name + " in" + reverseClass );
3731 doneIn = function() {
3733 if ( !sequential ) {
3741 .removeClass( "out in reverse " + name )
3744 toggleViewportClass();
3746 // In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition
3747 // This ensures we jump to that spot after the fact, if we aren't there already.
3748 if ( $.mobile.window.scrollTop() !== toScroll ) {
3752 deferred.resolve( name, reverse, $to, $from, true );
3755 toggleViewportClass();
3757 if ( $from && !none ) {
3764 return deferred.promise();
3768 // generate the handlers from the above
3769 var sequentialHandler = createHandler(),
3770 simultaneousHandler = createHandler( false ),
3771 defaultGetMaxScrollForTransition = function() {
3772 return $.mobile.getScreenHeight() * 3;
3775 // Make our transition handler the public default.
3776 $.mobile.defaultTransitionHandler = sequentialHandler;
3778 //transition handler dictionary for 3rd party transitions
3779 $.mobile.transitionHandlers = {
3780 "default": $.mobile.defaultTransitionHandler,
3781 "sequential": sequentialHandler,
3782 "simultaneous": simultaneousHandler
3785 $.mobile.transitionFallbacks = {};
3787 // If transition is defined, check if css 3D transforms are supported, and if not, if a fallback is specified
3788 $.mobile._maybeDegradeTransition = function( transition ) {
3789 if ( transition && !$.support.cssTransform3d && $.mobile.transitionFallbacks[ transition ] ) {
3790 transition = $.mobile.transitionFallbacks[ transition ];
3796 // Set the getMaxScrollForTransition to default if no implementation was set by user
3797 $.mobile.getMaxScrollForTransition = $.mobile.getMaxScrollForTransition || defaultGetMaxScrollForTransition;
3800 (function( $, undefined ) {
3802 //define vars for interal use
3803 var $window = $.mobile.window,
3804 $html = $( 'html' ),
3805 $head = $( 'head' ),
3807 // NOTE: path extensions dependent on core attributes. Moved here to remove deps from
3808 // $.mobile.path definition
3809 path = $.extend($.mobile.path, {
3811 //return the substring of a filepath before the sub-page key, for making a server request
3812 getFilePath: function( path ) {
3813 var splitkey = '&' + $.mobile.subPageUrlKey;
3814 return path && path.split( splitkey )[0].split( dialogHashKey )[0];
3817 //check if the specified url refers to the first page in the main application document.
3818 isFirstPageUrl: function( url ) {
3819 // We only deal with absolute paths.
3820 var u = path.parseUrl( path.makeUrlAbsolute( url, this.documentBase ) ),
3822 // Does the url have the same path as the document?
3823 samePath = u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ),
3825 // Get the first page element.
3826 fp = $.mobile.firstPage,
3828 // Get the id of the first page element if it has one.
3829 fpId = fp && fp[0] ? fp[0].id : undefined;
3831 // The url refers to the first page if the path matches the document and
3832 // it either has no hash value, or the hash is exactly equal to the id of the
3833 // first page element.
3834 return samePath && ( !u.hash || u.hash === "#" || ( fpId && u.hash.replace( /^#/, "" ) === fpId ) );
3837 // Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
3838 // requests if the document doing the request was loaded via the file:// protocol.
3839 // This is usually to allow the application to "phone home" and fetch app specific
3840 // data. We normally let the browser handle external/cross-domain urls, but if the
3841 // allowCrossDomainPages option is true, we will allow cross-domain http/https
3842 // requests to go through our page loading logic.
3843 isPermittedCrossDomainRequest: function( docUrl, reqUrl ) {
3844 return $.mobile.allowCrossDomainPages &&
3845 docUrl.protocol === "file:" &&
3846 reqUrl.search( /^https?:/ ) !== -1;
3850 // used to track last vclicked element to make sure its value is added to form data
3851 $lastVClicked = null,
3853 //will be defined when a link is clicked and given an active class
3854 $activeClickedLink = null,
3856 // resolved on domready
3857 domreadyDeferred = $.Deferred(),
3859 //urlHistory is purely here to make guesses at whether the back or forward button was clicked
3860 //and provide an appropriate transition
3861 urlHistory = $.mobile.navigate.history,
3863 //define first selector to receive focus when a page is shown
3864 focusable = "[tabindex],a,button:visible,select:visible,input",
3866 //queue to hold simultanious page transitions
3867 pageTransitionQueue = [],
3869 //indicates whether or not page is in process of transitioning
3870 isPageTransitioning = false,
3872 //nonsense hash change key for dialogs, so they create a history entry
3873 dialogHashKey = "&ui-state=dialog",
3875 //existing base tag?
3876 $base = $head.children( "base" ),
3878 //tuck away the original document URL minus any fragment.
3879 documentUrl = path.documentUrl,
3881 //if the document has an embedded base tag, documentBase is set to its
3882 //initial value. If a base tag does not exist, then we default to the documentUrl.
3883 documentBase = path.documentBase,
3885 //cache the comparison once.
3886 documentBaseDiffers = path.documentBaseDiffers,
3888 getScreenHeight = $.mobile.getScreenHeight;
3890 //base element management, defined depending on dynamic base tag support
3891 var base = $.support.dynamicBaseTag ? {
3893 //define base element, for use in routing asset urls that are referenced in Ajax-requested markup
3894 element: ( $base.length ? $base : $( "<base>", { href: documentBase.hrefNoHash } ).prependTo( $head ) ),
3896 //set the generated BASE element's href attribute to a new page's base path
3897 set: function( href ) {
3898 href = path.parseUrl(href).hrefNoHash;
3899 base.element.attr( "href", path.makeUrlAbsolute( href, documentBase ) );
3902 //set the generated BASE element's href attribute to a new page's base path
3904 base.element.attr( "href", documentBase.hrefNoSearch );
3910 //return the original document url
3911 $.mobile.getDocumentUrl = path.getDocumentUrl;
3913 //return the original document base url
3914 $.mobile.getDocumentBase = path.getDocumentBase;
3916 /* internal utility functions */
3918 // NOTE Issue #4950 Android phonegap doesn't navigate back properly
3919 // when a full page refresh has taken place. It appears that hashchange
3920 // and replacestate history alterations work fine but we need to support
3921 // both forms of history traversal in our code that uses backward history
3923 $.mobile.back = function() {
3924 var nav = window.navigator;
3926 // if the setting is on and the navigator object is
3927 // available use the phonegap navigation capability
3928 if( this.phonegapNavigationEnabled &&
3931 nav.app.backHistory ){
3932 nav.app.backHistory();
3934 window.history.back();
3938 //direct focus to the page title, or otherwise first focusable element
3939 $.mobile.focusPage = function ( page ) {
3940 var autofocus = page.find( "[autofocus]" ),
3941 pageTitle = page.find( ".ui-title:eq(0)" );
3943 if ( autofocus.length ) {
3948 if ( pageTitle.length ) {
3955 //remove active classes after page transition or error
3956 function removeActiveLinkClass( forceRemoval ) {
3957 if ( !!$activeClickedLink && ( !$activeClickedLink.closest( "." + $.mobile.activePageClass ).length || forceRemoval ) ) {
3958 $activeClickedLink.removeClass( $.mobile.activeBtnClass );
3960 $activeClickedLink = null;
3963 function releasePageTransitionLock() {
3964 isPageTransitioning = false;
3965 if ( pageTransitionQueue.length > 0 ) {
3966 $.mobile.changePage.apply( null, pageTransitionQueue.pop() );
3970 // Save the last scroll distance per page, before it is hidden
3971 var setLastScrollEnabled = true,
3972 setLastScroll, delayedSetLastScroll;
3974 setLastScroll = function() {
3975 // this barrier prevents setting the scroll value based on the browser
3976 // scrolling the window based on a hashchange
3977 if ( !setLastScrollEnabled ) {
3981 var active = $.mobile.urlHistory.getActive();
3984 var lastScroll = $window.scrollTop();
3986 // Set active page's lastScroll prop.
3987 // If the location we're scrolling to is less than minScrollBack, let it go.
3988 active.lastScroll = lastScroll < $.mobile.minScrollBack ? $.mobile.defaultHomeScroll : lastScroll;
3992 // bind to scrollstop to gather scroll position. The delay allows for the hashchange
3993 // event to fire and disable scroll recording in the case where the browser scrolls
3994 // to the hash targets location (sometimes the top of the page). once pagechange fires
3995 // getLastScroll is again permitted to operate
3996 delayedSetLastScroll = function() {
3997 setTimeout( setLastScroll, 100 );
4000 // disable an scroll setting when a hashchange has been fired, this only works
4001 // because the recording of the scroll position is delayed for 100ms after
4002 // the browser might have changed the position because of the hashchange
4003 $window.bind( $.support.pushState ? "popstate" : "hashchange", function() {
4004 setLastScrollEnabled = false;
4007 // handle initial hashchange from chrome :(
4008 $window.one( $.support.pushState ? "popstate" : "hashchange", function() {
4009 setLastScrollEnabled = true;
4012 // wait until the mobile page container has been determined to bind to pagechange
4013 $window.one( "pagecontainercreate", function() {
4014 // once the page has changed, re-enable the scroll recording
4015 $.mobile.pageContainer.bind( "pagechange", function() {
4017 setLastScrollEnabled = true;
4019 // remove any binding that previously existed on the get scroll
4020 // which may or may not be different than the scroll element determined for
4021 // this page previously
4022 $window.unbind( "scrollstop", delayedSetLastScroll );
4024 // determine and bind to the current scoll element which may be the window
4025 // or in the case of touch overflow the element with touch overflow
4026 $window.bind( "scrollstop", delayedSetLastScroll );
4030 // bind to scrollstop for the first page as "pagechange" won't be fired in that case
4031 $window.bind( "scrollstop", delayedSetLastScroll );
4033 // No-op implementation of transition degradation
4034 $.mobile._maybeDegradeTransition = $.mobile._maybeDegradeTransition || function( transition ) {
4038 //function for transitioning between two existing pages
4039 function transitionPages( toPage, fromPage, transition, reverse ) {
4041 //trigger before show/hide events
4042 fromPage.data( "mobile-page" )._trigger( "beforehide", null, { nextPage: toPage } );
4045 toPage.data( "mobile-page" )._trigger( "beforeshow", null, { prevPage: fromPage || $( "" ) } );
4048 $.mobile.hidePageLoadingMsg();
4050 transition = $.mobile._maybeDegradeTransition( transition );
4052 //find the transition handler for the specified transition. If there
4053 //isn't one in our transitionHandlers dictionary, use the default one.
4054 //call the handler immediately to kick-off the transition.
4055 var th = $.mobile.transitionHandlers[ transition || "default" ] || $.mobile.defaultTransitionHandler,
4056 promise = th( transition, reverse, toPage, fromPage );
4058 promise.done(function() {
4059 //trigger show/hide events
4061 fromPage.data( "mobile-page" )._trigger( "hide", null, { nextPage: toPage } );
4064 //trigger pageshow, define prevPage as either fromPage or empty jQuery obj
4065 toPage.data( "mobile-page" )._trigger( "show", null, { prevPage: fromPage || $( "" ) } );
4071 //simply set the active page's minimum height to screen height, depending on orientation
4072 $.mobile.resetActivePageHeight = function resetActivePageHeight( height ) {
4073 var aPage = $( "." + $.mobile.activePageClass ),
4074 aPagePadT = parseFloat( aPage.css( "padding-top" ) ),
4075 aPagePadB = parseFloat( aPage.css( "padding-bottom" ) ),
4076 aPageBorderT = parseFloat( aPage.css( "border-top-width" ) ),
4077 aPageBorderB = parseFloat( aPage.css( "border-bottom-width" ) );
4079 height = ( typeof height === "number" )? height : getScreenHeight();
4081 aPage.css( "min-height", height - aPagePadT - aPagePadB - aPageBorderT - aPageBorderB );
4084 //shared page enhancements
4085 function enhancePage( $page, role ) {
4086 // If a role was specified, make sure the data-role attribute
4087 // on the page element is in sync.
4089 $page.attr( "data-" + $.mobile.ns + "role", role );
4096 // determine the current base url
4097 function findBaseWithDefault() {
4098 var closestBase = ( $.mobile.activePage && getClosestBaseUrl( $.mobile.activePage ) );
4099 return closestBase || documentBase.hrefNoHash;
4102 /* exposed $.mobile methods */
4104 //animation complete callback
4105 $.fn.animationComplete = function( callback ) {
4106 if ( $.support.cssTransitions ) {
4107 return $( this ).one( 'webkitAnimationEnd animationend', callback );
4110 // defer execution for consistency between webkit/non webkit
4111 setTimeout( callback, 0 );
4116 //expose path object on $.mobile
4117 $.mobile.path = path;
4119 //expose base object on $.mobile
4120 $.mobile.base = base;
4123 $.mobile.urlHistory = urlHistory;
4125 $.mobile.dialogHashKey = dialogHashKey;
4127 //enable cross-domain page support
4128 $.mobile.allowCrossDomainPages = false;
4130 $.mobile._bindPageRemove = function() {
4131 var page = $( this );
4133 // when dom caching is not enabled or the page is embedded bind to remove the page on hide
4134 if ( !page.data( "mobile-page" ).options.domCache &&
4135 page.is( ":jqmData(external-page='true')" ) ) {
4137 page.bind( 'pagehide.remove', function( e ) {
4138 var $this = $( this ),
4139 prEvent = new $.Event( "pageremove" );
4141 $this.trigger( prEvent );
4143 if ( !prEvent.isDefaultPrevented() ) {
4144 $this.removeWithDependents();
4150 // Load a page into the DOM.
4151 $.mobile.loadPage = function( url, options ) {
4152 // This function uses deferred notifications to let callers
4153 // know when the page is done loading, or if an error has occurred.
4154 var deferred = $.Deferred(),
4156 // The default loadPage options with overrides specified by
4158 settings = $.extend( {}, $.mobile.loadPage.defaults, options ),
4160 // The DOM element for the page after it has been loaded.
4163 // If the reloadPage option is true, and the page is already
4164 // in the DOM, dupCachedPage will be set to the page element
4165 // so that it can be removed after the new version of the
4166 // page is loaded off the network.
4167 dupCachedPage = null,
4169 // The absolute version of the URL passed into the function. This
4170 // version of the URL may contain dialog/subpage params in it.
4171 absUrl = path.makeUrlAbsolute( url, findBaseWithDefault() );
4173 // If the caller provided data, and we're using "get" request,
4174 // append the data to the URL.
4175 if ( settings.data && settings.type === "get" ) {
4176 absUrl = path.addSearchParams( absUrl, settings.data );
4177 settings.data = undefined;
4180 // If the caller is using a "post" request, reloadPage must be true
4181 if ( settings.data && settings.type === "post" ) {
4182 settings.reloadPage = true;
4185 // The absolute version of the URL minus any dialog/subpage params.
4186 // In otherwords the real URL of the page to be loaded.
4187 var fileUrl = path.getFilePath( absUrl ),
4189 // The version of the Url actually stored in the data-url attribute of
4190 // the page. For embedded pages, it is just the id of the page. For pages
4191 // within the same domain as the document base, it is the site relative
4192 // path. For cross-domain pages (Phone Gap only) the entire absolute Url
4193 // used to load the page.
4194 dataUrl = path.convertUrlToDataUrl( absUrl );
4196 // Make sure we have a pageContainer to work with.
4197 settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
4199 // Check to see if the page already exists in the DOM.
4200 // NOTE do _not_ use the :jqmData psuedo selector because parenthesis
4201 // are a valid url char and it breaks on the first occurence
4202 page = settings.pageContainer.children( "[data-" + $.mobile.ns +"url='" + dataUrl + "']" );
4204 // If we failed to find the page, check to see if the url is a
4205 // reference to an embedded page. If so, it may have been dynamically
4206 // injected by a developer, in which case it would be lacking a data-url
4207 // attribute and in need of enhancement.
4208 if ( page.length === 0 && dataUrl && !path.isPath( dataUrl ) ) {
4209 page = settings.pageContainer.children( "#" + dataUrl )
4210 .attr( "data-" + $.mobile.ns + "url", dataUrl )
4211 .jqmData( "url", dataUrl );
4215 // If we failed to find a page in the DOM, check the URL to see if it
4216 // refers to the first page in the application. If it isn't a reference
4217 // to the first page and refers to non-existent embedded page, error out.
4218 if ( page.length === 0 ) {
4219 if ( $.mobile.firstPage && path.isFirstPageUrl( fileUrl ) ) {
4220 // Check to make sure our cached-first-page is actually
4221 // in the DOM. Some user deployed apps are pruning the first
4222 // page from the DOM for various reasons, we check for this
4223 // case here because we don't want a first-page with an id
4224 // falling through to the non-existent embedded page error
4225 // case. If the first-page is not in the DOM, then we let
4226 // things fall through to the ajax loading code below so
4227 // that it gets reloaded.
4228 if ( $.mobile.firstPage.parent().length ) {
4229 page = $( $.mobile.firstPage );
4231 } else if ( path.isEmbeddedPage( fileUrl ) ) {
4232 deferred.reject( absUrl, options );
4233 return deferred.promise();
4237 // If the page we are interested in is already in the DOM,
4238 // and the caller did not indicate that we should force a
4239 // reload of the file, we are done. Otherwise, track the
4240 // existing page as a duplicated.
4241 if ( page.length ) {
4242 if ( !settings.reloadPage ) {
4243 enhancePage( page, settings.role );
4244 deferred.resolve( absUrl, options, page );
4245 //if we are reloading the page make sure we update the base if its not a prefetch
4246 if( base && !options.prefetch ){
4249 return deferred.promise();
4251 dupCachedPage = page;
4253 var mpc = settings.pageContainer,
4254 pblEvent = new $.Event( "pagebeforeload" ),
4255 triggerData = { url: url, absUrl: absUrl, dataUrl: dataUrl, deferred: deferred, options: settings };
4257 // Let listeners know we're about to load a page.
4258 mpc.trigger( pblEvent, triggerData );
4260 // If the default behavior is prevented, stop here!
4261 if ( pblEvent.isDefaultPrevented() ) {
4262 return deferred.promise();
4265 if ( settings.showLoadMsg ) {
4267 // This configurable timeout allows cached pages a brief delay to load without showing a message
4268 var loadMsgDelay = setTimeout(function() {
4269 $.mobile.showPageLoadingMsg();
4270 }, settings.loadMsgDelay ),
4272 // Shared logic for clearing timeout and removing message.
4273 hideMsg = function() {
4275 // Stop message show timer
4276 clearTimeout( loadMsgDelay );
4278 // Hide loading message
4279 $.mobile.hidePageLoadingMsg();
4282 // Reset base to the default document base.
4283 // only reset if we are not prefetching
4284 if ( base && typeof options.prefetch === "undefined" ) {
4288 if ( !( $.mobile.allowCrossDomainPages || path.isSameDomain( documentUrl, absUrl ) ) ) {
4289 deferred.reject( absUrl, options );
4291 // Load the new page.
4294 type: settings.type,
4295 data: settings.data,
4296 contentType: settings.contentType,
4298 success: function( html, textStatus, xhr ) {
4299 //pre-parse html to check for a data-url,
4300 //use it as the new fileUrl, base path, etc
4301 var all = $( "<div></div>" ),
4304 newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1,
4306 // TODO handle dialogs again
4307 pageElemRegex = new RegExp( "(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?page[\"']?[^>]*>)" ),
4308 dataUrlRegex = new RegExp( "\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?" );
4311 // data-url must be provided for the base tag so resource requests can be directed to the
4312 // correct url. loading into a temprorary element makes these requests immediately
4313 if ( pageElemRegex.test( html ) &&
4315 dataUrlRegex.test( RegExp.$1 ) &&
4317 url = fileUrl = path.getFilePath( $( "<div>" + RegExp.$1 + "</div>" ).text() );
4319 //dont update the base tag if we are prefetching
4320 if ( base && typeof options.prefetch === "undefined") {
4321 base.set( fileUrl );
4324 //workaround to allow scripts to execute when included in page divs
4325 all.get( 0 ).innerHTML = html;
4326 page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first();
4328 //if page elem couldn't be found, create one and insert the body element's contents
4329 if ( !page.length ) {
4330 page = $( "<div data-" + $.mobile.ns + "role='page'>" + ( html.split( /<\/?body[^>]*>/gmi )[1] || "" ) + "</div>" );
4333 if ( newPageTitle && !page.jqmData( "title" ) ) {
4334 if ( ~newPageTitle.indexOf( "&" ) ) {
4335 newPageTitle = $( "<div>" + newPageTitle + "</div>" ).text();
4337 page.jqmData( "title", newPageTitle );
4340 //rewrite src and href attrs to use a base url
4341 if ( !$.support.dynamicBaseTag ) {
4342 var newPath = path.get( fileUrl );
4343 page.find( "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]" ).each(function() {
4344 var thisAttr = $( this ).is( '[href]' ) ? 'href' :
4345 $( this ).is( '[src]' ) ? 'src' : 'action',
4346 thisUrl = $( this ).attr( thisAttr );
4348 // XXX_jblas: We need to fix this so that it removes the document
4349 // base URL, and then prepends with the new page URL.
4350 //if full path exists and is same, chop it - helps IE out
4351 thisUrl = thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' );
4353 if ( !/^(\w+:|#|\/)/.test( thisUrl ) ) {
4354 $( this ).attr( thisAttr, newPath + thisUrl );
4359 //append to page and enhance
4360 // TODO taging a page with external to make sure that embedded pages aren't removed
4361 // by the various page handling code is bad. Having page handling code in many
4362 // places is bad. Solutions post 1.0
4364 .attr( "data-" + $.mobile.ns + "url", path.convertUrlToDataUrl( fileUrl ) )
4365 .attr( "data-" + $.mobile.ns + "external-page", true )
4366 .appendTo( settings.pageContainer );
4368 // wait for page creation to leverage options defined on widget
4369 page.one( 'pagecreate', $.mobile._bindPageRemove );
4371 enhancePage( page, settings.role );
4373 // Enhancing the page may result in new dialogs/sub pages being inserted
4374 // into the DOM. If the original absUrl refers to a sub-page, that is the
4375 // real page we are interested in.
4376 if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) {
4377 page = settings.pageContainer.children( "[data-" + $.mobile.ns +"url='" + dataUrl + "']" );
4380 // Remove loading message.
4381 if ( settings.showLoadMsg ) {
4385 // Add the page reference and xhr to our triggerData.
4386 triggerData.xhr = xhr;
4387 triggerData.textStatus = textStatus;
4388 triggerData.page = page;
4390 // Let listeners know the page loaded successfully.
4391 settings.pageContainer.trigger( "pageload", triggerData );
4393 deferred.resolve( absUrl, options, page, dupCachedPage );
4395 error: function( xhr, textStatus, errorThrown ) {
4396 //set base back to current path
4398 base.set( path.get() );
4401 // Add error info to our triggerData.
4402 triggerData.xhr = xhr;
4403 triggerData.textStatus = textStatus;
4404 triggerData.errorThrown = errorThrown;
4406 var plfEvent = new $.Event( "pageloadfailed" );
4408 // Let listeners know the page load failed.
4409 settings.pageContainer.trigger( plfEvent, triggerData );
4411 // If the default behavior is prevented, stop here!
4412 // Note that it is the responsibility of the listener/handler
4413 // that called preventDefault(), to resolve/reject the
4414 // deferred object within the triggerData.
4415 if ( plfEvent.isDefaultPrevented() ) {
4419 // Remove loading message.
4420 if ( settings.showLoadMsg ) {
4422 // Remove loading message.
4425 // show error message
4426 $.mobile.showPageLoadingMsg( $.mobile.pageLoadErrorMessageTheme, $.mobile.pageLoadErrorMessage, true );
4429 setTimeout( $.mobile.hidePageLoadingMsg, 1500 );
4432 deferred.reject( absUrl, options );
4437 return deferred.promise();
4440 $.mobile.loadPage.defaults = {
4444 role: undefined, // By default we rely on the role defined by the @data-role attribute.
4446 pageContainer: undefined,
4447 loadMsgDelay: 50 // This delay allows loads that pull from browser cache to occur without showing the loading message.
4450 // Show a specific page in the page container.
4451 $.mobile.changePage = function( toPage, options ) {
4452 // If we are in the midst of a transition, queue the current request.
4453 // We'll call changePage() once we're done with the current transition to
4454 // service the request.
4455 if ( isPageTransitioning ) {
4456 pageTransitionQueue.unshift( arguments );
4460 var settings = $.extend( {}, $.mobile.changePage.defaults, options ), isToPageString;
4462 // Make sure we have a pageContainer to work with.
4463 settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
4465 // Make sure we have a fromPage.
4466 settings.fromPage = settings.fromPage || $.mobile.activePage;
4468 isToPageString = (typeof toPage === "string");
4470 var mpc = settings.pageContainer,
4471 pbcEvent = new $.Event( "pagebeforechange" ),
4472 triggerData = { toPage: toPage, options: settings };
4474 // NOTE: preserve the original target as the dataUrl value will be simplified
4475 // eg, removing ui-state, and removing query params from the hash
4476 // this is so that users who want to use query params have access to them
4477 // in the event bindings for the page life cycle See issue #5085
4478 if ( isToPageString ) {
4479 // if the toPage is a string simply convert it
4480 triggerData.absUrl = path.makeUrlAbsolute( toPage, findBaseWithDefault() );
4482 // if the toPage is a jQuery object grab the absolute url stored
4483 // in the loadPage callback where it exists
4484 triggerData.absUrl = toPage.data( 'absUrl' );
4487 // Let listeners know we're about to change the current page.
4488 mpc.trigger( pbcEvent, triggerData );
4490 // If the default behavior is prevented, stop here!
4491 if ( pbcEvent.isDefaultPrevented() ) {
4495 // We allow "pagebeforechange" observers to modify the toPage in the trigger
4496 // data to allow for redirects. Make sure our toPage is updated.
4498 // We also need to re-evaluate whether it is a string, because an object can
4499 // also be replaced by a string
4501 toPage = triggerData.toPage;
4502 isToPageString = (typeof toPage === "string");
4504 // Set the isPageTransitioning flag to prevent any requests from
4505 // entering this method while we are in the midst of loading a page
4506 // or transitioning.
4507 isPageTransitioning = true;
4509 // If the caller passed us a url, call loadPage()
4510 // to make sure it is loaded into the DOM. We'll listen
4511 // to the promise object it returns so we know when
4512 // it is done loading or if an error ocurred.
4513 if ( isToPageString ) {
4514 // preserve the original target as the dataUrl value will be simplified
4515 // eg, removing ui-state, and removing query params from the hash
4516 // this is so that users who want to use query params have access to them
4517 // in the event bindings for the page life cycle See issue #5085
4518 settings.target = toPage;
4520 $.mobile.loadPage( toPage, settings )
4521 .done(function( url, options, newPage, dupCachedPage ) {
4522 isPageTransitioning = false;
4523 options.duplicateCachedPage = dupCachedPage;
4525 // store the original absolute url so that it can be provided
4526 // to events in the triggerData of the subsequent changePage call
4527 newPage.data( 'absUrl', triggerData.absUrl );
4528 $.mobile.changePage( newPage, options );
4530 .fail(function( url, options ) {
4532 //clear out the active button state
4533 removeActiveLinkClass( true );
4535 //release transition lock so navigation is free again
4536 releasePageTransitionLock();
4537 settings.pageContainer.trigger( "pagechangefailed", triggerData );
4542 // If we are going to the first-page of the application, we need to make
4543 // sure settings.dataUrl is set to the application document url. This allows
4544 // us to avoid generating a document url with an id hash in the case where the
4545 // first-page of the document has an id attribute specified.
4546 if ( toPage[ 0 ] === $.mobile.firstPage[ 0 ] && !settings.dataUrl ) {
4547 settings.dataUrl = documentUrl.hrefNoHash;
4550 // The caller passed us a real page DOM element. Update our
4551 // internal state and then trigger a transition to the page.
4552 var fromPage = settings.fromPage,
4553 url = ( settings.dataUrl && path.convertUrlToDataUrl( settings.dataUrl ) ) || toPage.jqmData( "url" ),
4554 // The pageUrl var is usually the same as url, except when url is obscured as a dialog url. pageUrl always contains the file path
4556 fileUrl = path.getFilePath( url ),
4557 active = urlHistory.getActive(),
4558 activeIsInitialPage = urlHistory.activeIndex === 0,
4560 pageTitle = document.title,
4561 isDialog = settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog";
4564 // By default, we prevent changePage requests when the fromPage and toPage
4565 // are the same element, but folks that generate content manually/dynamically
4566 // and reuse pages want to be able to transition to the same page. To allow
4567 // this, they will need to change the default value of allowSamePageTransition
4568 // to true, *OR*, pass it in as an option when they manually call changePage().
4569 // It should be noted that our default transition animations assume that the
4570 // formPage and toPage are different elements, so they may behave unexpectedly.
4571 // It is up to the developer that turns on the allowSamePageTransitiona option
4572 // to either turn off transition animations, or make sure that an appropriate
4573 // animation transition is used.
4574 if ( fromPage && fromPage[0] === toPage[0] && !settings.allowSamePageTransition ) {
4575 isPageTransitioning = false;
4576 mpc.trigger( "pagechange", triggerData );
4578 // Even if there is no page change to be done, we should keep the urlHistory in sync with the hash changes
4579 if ( settings.fromHashChange ) {
4580 urlHistory.direct({ url: url });
4586 // We need to make sure the page we are given has already been enhanced.
4587 enhancePage( toPage, settings.role );
4589 // If the changePage request was sent from a hashChange event, check to see if the
4590 // page is already within the urlHistory stack. If so, we'll assume the user hit
4591 // the forward/back button and will try to match the transition accordingly.
4592 if ( settings.fromHashChange ) {
4593 historyDir = options.direction === "back" ? -1 : 1;
4596 // Kill the keyboard.
4597 // XXX_jblas: We need to stop crawling the entire document to kill focus. Instead,
4598 // we should be tracking focus with a delegate() handler so we already have
4599 // the element in hand at this point.
4600 // Wrap this in a try/catch block since IE9 throw "Unspecified error" if document.activeElement
4601 // is undefined when we are in an IFrame.
4603 if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== 'body' ) {
4604 $( document.activeElement ).blur();
4606 $( "input:focus, textarea:focus, select:focus" ).blur();
4610 // 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
4611 var alreadyThere = false;
4613 // If we're displaying the page as a dialog, we don't want the url
4614 // for the dialog content to be used in the hash. Instead, we want
4615 // to append the dialogHashKey to the url of the current page.
4616 if ( isDialog && active ) {
4617 // on the initial page load active.url is undefined and in that case should
4618 // be an empty string. Moving the undefined -> empty string back into
4619 // urlHistory.addNew seemed imprudent given undefined better represents
4622 // If we are at a place in history that once belonged to a dialog, reuse
4623 // this state without adding to urlHistory and without modifying the hash.
4624 // However, if a dialog is already displayed at this point, and we're
4625 // about to display another dialog, then we must add another hash and
4626 // history entry on top so that one may navigate back to the original dialog
4628 active.url.indexOf( dialogHashKey ) > -1 &&
4629 $.mobile.activePage &&
4630 !$.mobile.activePage.is( ".ui-dialog" ) &&
4631 urlHistory.activeIndex > 0 ) {
4632 settings.changeHash = false;
4633 alreadyThere = true;
4636 // Normally, we tack on a dialog hash key, but if this is the location of a stale dialog,
4637 // we reuse the URL from the entry
4638 url = ( active.url || "" );
4640 // account for absolute urls instead of just relative urls use as hashes
4641 if( !alreadyThere && url.indexOf("#") > -1 ) {
4642 url += dialogHashKey;
4644 url += "#" + dialogHashKey;
4647 // tack on another dialogHashKey if this is the same as the initial hash
4648 // this makes sure that a history entry is created for this dialog
4649 if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) {
4650 url += dialogHashKey;
4654 // if title element wasn't found, try the page div data attr too
4655 // If this is a deep-link or a reload ( active === undefined ) then just use pageTitle
4656 var newPageTitle = ( !active )? pageTitle : toPage.jqmData( "title" ) || toPage.children( ":jqmData(role='header')" ).find( ".ui-title" ).text();
4657 if ( !!newPageTitle && pageTitle === document.title ) {
4658 pageTitle = newPageTitle;
4660 if ( !toPage.jqmData( "title" ) ) {
4661 toPage.jqmData( "title", pageTitle );
4664 // Make sure we have a transition defined.
4665 settings.transition = settings.transition ||
4666 ( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined ) ||
4667 ( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition );
4669 //add page to history stack if it's not back or forward
4670 if ( !historyDir && alreadyThere ) {
4671 urlHistory.getActive().pageUrl = pageUrl;
4674 // Set the location hash.
4675 if ( url && !settings.fromHashChange ) {
4678 // rebuilding the hash here since we loose it earlier on
4679 // TODO preserve the originally passed in path
4680 if( !path.isPath( url ) && url.indexOf( "#" ) < 0 ) {
4684 // TODO the property names here are just silly
4686 transition: settings.transition,
4692 if ( settings.changeHash !== false && $.mobile.hashListeningEnabled ) {
4693 $.mobile.navigate( url, params, true);
4694 } else if ( toPage[ 0 ] !== $.mobile.firstPage[ 0 ] ) {
4695 $.mobile.navigate.history.add( url, params );
4700 document.title = pageTitle;
4702 //set "toPage" as activePage
4703 $.mobile.activePage = toPage;
4705 // If we're navigating back in the URL history, set reverse accordingly.
4706 settings.reverse = settings.reverse || historyDir < 0;
4708 transitionPages( toPage, fromPage, settings.transition, settings.reverse )
4709 .done(function( name, reverse, $to, $from, alreadyFocused ) {
4710 removeActiveLinkClass();
4712 //if there's a duplicateCachedPage, remove it from the DOM now that it's hidden
4713 if ( settings.duplicateCachedPage ) {
4714 settings.duplicateCachedPage.remove();
4717 // Send focus to the newly shown page. Moved from promise .done binding in transitionPages
4718 // itself to avoid ie bug that reports offsetWidth as > 0 (core check for visibility)
4719 // despite visibility: hidden addresses issue #2965
4720 // https://github.com/jquery/jquery-mobile/issues/2965
4721 if ( !alreadyFocused ) {
4722 $.mobile.focusPage( toPage );
4725 releasePageTransitionLock();
4726 mpc.trigger( "pagechange", triggerData );
4730 $.mobile.changePage.defaults = {
4731 transition: undefined,
4734 fromHashChange: false,
4735 role: undefined, // By default we rely on the role defined by the @data-role attribute.
4736 duplicateCachedPage: undefined,
4737 pageContainer: undefined,
4738 showLoadMsg: true, //loading message shows by default when pages are being fetched during changePage
4740 fromPage: undefined,
4741 allowSamePageTransition: false
4744 /* Event Bindings - hashchange, submit, and click */
4745 function findClosestLink( ele )
4748 // Look for the closest element with a nodeName of "a".
4749 // Note that we are checking if we have a valid nodeName
4750 // before attempting to access it. This is because the
4751 // node we get called with could have originated from within
4752 // an embedded SVG document where some symbol instance elements
4753 // don't have nodeName defined on them, or strings are of type
4754 // SVGAnimatedString.
4755 if ( ( typeof ele.nodeName === "string" ) && ele.nodeName.toLowerCase() === "a" ) {
4758 ele = ele.parentNode;
4763 // The base URL for any given element depends on the page it resides in.
4764 function getClosestBaseUrl( ele )
4766 // Find the closest page and extract out its url.
4767 var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ),
4768 base = documentBase.hrefNoHash;
4770 if ( !url || !path.isPath( url ) ) {
4774 return path.makeUrlAbsolute( url, base);
4777 //The following event bindings should be bound after mobileinit has been triggered
4778 //the following deferred is resolved in the init file
4779 $.mobile.navreadyDeferred = $.Deferred();
4780 $.mobile._registerInternalEvents = function() {
4781 var getAjaxFormData = function( $form, calculateOnly ) {
4782 var url, ret = true, formData, vclickedName, method;
4784 if ( !$.mobile.ajaxEnabled ||
4785 // test that the form is, itself, ajax false
4786 $form.is( ":jqmData(ajax='false')" ) ||
4787 // test that $.mobile.ignoreContentEnabled is set and
4788 // the form or one of it's parents is ajax=false
4789 !$form.jqmHijackable().length ||
4790 $form.attr( "target" ) ) {
4794 url = $form.attr( "action" );
4795 method = ( $form.attr( "method" ) || "get" ).toLowerCase();
4797 // If no action is specified, browsers default to using the
4798 // URL of the document containing the form. Since we dynamically
4799 // pull in pages from external documents, the form should submit
4800 // to the URL for the source document of the page containing
4803 // Get the @data-url for the page containing the form.
4804 url = getClosestBaseUrl( $form );
4806 // NOTE: If the method is "get", we need to strip off the query string
4807 // because it will get replaced with the new form data. See issue #5710.
4808 if ( method === "get" ) {
4809 url = path.parseUrl( url ).hrefNoSearch;
4812 if ( url === documentBase.hrefNoHash ) {
4813 // The url we got back matches the document base,
4814 // which means the page must be an internal/embedded page,
4815 // so default to using the actual document url as a browser
4817 url = documentUrl.hrefNoSearch;
4821 url = path.makeUrlAbsolute( url, getClosestBaseUrl( $form ) );
4823 if ( ( path.isExternal( url ) && !path.isPermittedCrossDomainRequest( documentUrl, url ) ) ) {
4827 if ( !calculateOnly ) {
4828 formData = $form.serializeArray();
4830 if ( $lastVClicked && $lastVClicked[ 0 ].form === $form[ 0 ] ) {
4831 vclickedName = $lastVClicked.attr( "name" );
4832 if ( vclickedName ) {
4833 // Make sure the last clicked element is included in the form
4834 $.each( formData, function( key, value ) {
4835 if ( value.name === vclickedName ) {
4836 // Unset vclickedName - we've found it in the serialized data already
4841 if ( vclickedName ) {
4842 formData.push( { name: vclickedName, value: $lastVClicked.attr( "value" ) } );
4851 data: $.param( formData ),
4852 transition: $form.jqmData( "transition" ),
4853 reverse: $form.jqmData( "direction" ) === "reverse",
4862 //bind to form submit events, handle with Ajax
4863 $.mobile.document.delegate( "form", "submit", function( event ) {
4864 var formData = getAjaxFormData( $( this ) );
4867 $.mobile.changePage( formData.url, formData.options );
4868 event.preventDefault();
4872 //add active state on vclick
4873 $.mobile.document.bind( "vclick", function( event ) {
4874 var $btn, btnEls, target = event.target, needClosest = false;
4875 // if this isn't a left click we don't care. Its important to note
4876 // that when the virtual event is generated it will create the which attr
4877 if ( event.which > 1 || !$.mobile.linkBindingEnabled ) {
4881 // Record that this element was clicked, in case we need it for correct
4882 // form submission during the "submit" handler above
4883 $lastVClicked = $( target );
4885 // Try to find a target element to which the active class will be applied
4886 if ( $.data( target, "mobile-button" ) ) {
4887 // If the form will not be submitted via AJAX, do not add active class
4888 if ( !getAjaxFormData( $( target ).closest( "form" ), true ) ) {
4891 // We will apply the active state to this button widget - the parent
4892 // of the input that was clicked will have the associated data
4893 if ( target.parentNode ) {
4894 target = target.parentNode;
4897 target = findClosestLink( target );
4898 if ( !( target && path.parseUrl( target.getAttribute( "href" ) || "#" ).hash !== "#" ) ) {
4902 // TODO teach $.mobile.hijackable to operate on raw dom elements so the
4903 // link wrapping can be avoided
4904 if ( !$( target ).jqmHijackable().length ) {
4909 // Avoid calling .closest by using the data set during .buttonMarkup()
4910 // List items have the button data in the parent of the element clicked
4911 if ( !!~target.className.indexOf( "ui-link-inherit" ) ) {
4912 if ( target.parentNode ) {
4913 btnEls = $.data( target.parentNode, "buttonElements" );
4915 // Otherwise, look for the data on the target itself
4917 btnEls = $.data( target, "buttonElements" );
4919 // If found, grab the button's outer element
4921 target = btnEls.outer;
4927 // If the outer element wasn't found by the our heuristics, use .closest()
4928 if ( needClosest ) {
4929 $btn = $btn.closest( ".ui-btn" );
4932 if ( $btn.length > 0 && !$btn.hasClass( "ui-disabled" ) ) {
4933 removeActiveLinkClass( true );
4934 $activeClickedLink = $btn;
4935 $activeClickedLink.addClass( $.mobile.activeBtnClass );
4939 // click routing - direct to HTTP or Ajax, accordingly
4940 $.mobile.document.bind( "click", function( event ) {
4941 if ( !$.mobile.linkBindingEnabled || event.isDefaultPrevented() ) {
4945 var link = findClosestLink( event.target ), $link = $( link ), httpCleanup;
4947 // If there is no link associated with the click or its not a left
4948 // click we want to ignore the click
4949 // TODO teach $.mobile.hijackable to operate on raw dom elements so the link wrapping
4951 if ( !link || event.which > 1 || !$link.jqmHijackable().length ) {
4955 //remove active link class if external (then it won't be there if you come back)
4956 httpCleanup = function() {
4957 window.setTimeout(function() { removeActiveLinkClass( true ); }, 200 );
4960 //if there's a data-rel=back attr, go back in history
4961 if ( $link.is( ":jqmData(rel='back')" ) ) {
4966 var baseUrl = getClosestBaseUrl( $link ),
4968 //get href, if defined, otherwise default to empty hash
4969 href = path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl );
4971 //if ajax is disabled, exit early
4972 if ( !$.mobile.ajaxEnabled && !path.isEmbeddedPage( href ) ) {
4974 //use default click handling
4978 // XXX_jblas: Ideally links to application pages should be specified as
4979 // an url to the application document with a hash that is either
4980 // the site relative path or id to the page. But some of the
4981 // internal code that dynamically generates sub-pages for nested
4982 // lists and select dialogs, just write a hash in the link they
4983 // create. This means the actual URL path is based on whatever
4984 // the current value of the base tag is at the time this code
4985 // is called. For now we are just assuming that any url with a
4986 // hash in it is an application page reference.
4987 if ( href.search( "#" ) !== -1 ) {
4988 href = href.replace( /[^#]*#/, "" );
4990 //link was an empty hash meant purely
4991 //for interaction, so we ignore it.
4992 event.preventDefault();
4994 } else if ( path.isPath( href ) ) {
4995 //we have apath so make it the href we want to load.
4996 href = path.makeUrlAbsolute( href, baseUrl );
4998 //we have a simple id so use the documentUrl as its base.
4999 href = path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash );
5003 // Should we handle this link, or let the browser deal with it?
5004 var useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ),
5006 // Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
5007 // requests if the document doing the request was loaded via the file:// protocol.
5008 // This is usually to allow the application to "phone home" and fetch app specific
5009 // data. We normally let the browser handle external/cross-domain urls, but if the
5010 // allowCrossDomainPages option is true, we will allow cross-domain http/https
5011 // requests to go through our page loading logic.
5013 //check for protocol or rel and its not an embedded page
5014 //TODO overlap in logic from isExternal, rel=external check should be
5015 // moved into more comprehensive isExternalLink
5016 isExternal = useDefaultUrlHandling || ( path.isExternal( href ) && !path.isPermittedCrossDomainRequest( documentUrl, href ) );
5020 //use default click handling
5025 var transition = $link.jqmData( "transition" ),
5026 reverse = $link.jqmData( "direction" ) === "reverse" ||
5027 // deprecated - remove by 1.0
5028 $link.jqmData( "back" ),
5030 //this may need to be more specific as we use data-rel more
5031 role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined;
5033 $.mobile.changePage( href, { transition: transition, reverse: reverse, role: role, link: $link } );
5034 event.preventDefault();
5037 //prefetch pages when anchors with data-prefetch are encountered
5038 $.mobile.document.delegate( ".ui-page", "pageshow.prefetch", function() {
5040 $( this ).find( "a:jqmData(prefetch)" ).each(function() {
5041 var $link = $( this ),
5042 url = $link.attr( "href" );
5044 if ( url && $.inArray( url, urls ) === -1 ) {
5047 $.mobile.loadPage( url, { role: $link.attr( "data-" + $.mobile.ns + "rel" ),prefetch: true } );
5052 $.mobile._handleHashChange = function( url, data ) {
5053 //find first page via hash
5054 var to = path.stripHash(url),
5055 //transition is false if it's the first page, undefined otherwise (and may be overridden by default)
5056 transition = $.mobile.urlHistory.stack.length === 0 ? "none" : undefined,
5058 // default options for the changPage calls made after examining the current state
5059 // of the page and the hash, NOTE that the transition is derived from the previous
5061 changePageOptions = {
5063 fromHashChange: true,
5064 reverse: data.direction === "back"
5067 $.extend( changePageOptions, data, {
5068 transition: (urlHistory.getLast() || {}).transition || transition
5071 // special case for dialogs
5072 if ( urlHistory.activeIndex > 0 && to.indexOf( dialogHashKey ) > -1 && urlHistory.initialDst !== to ) {
5074 // If current active page is not a dialog skip the dialog and continue
5075 // in the same direction
5076 if ( $.mobile.activePage && !$.mobile.activePage.is( ".ui-dialog" ) ) {
5077 //determine if we're heading forward or backward and continue accordingly past
5078 //the current dialog
5079 if( data.direction === "back" ) {
5082 window.history.forward();
5085 // prevent changePage call
5088 // if the current active page is a dialog and we're navigating
5089 // to a dialog use the dialog objected saved in the stack
5091 var active = $.mobile.urlHistory.getActive();
5093 // make sure to set the role, transition and reversal
5094 // as most of this is lost by the domCache cleaning
5095 $.extend( changePageOptions, {
5097 transition: active.transition,
5098 reverse: data.direction === "back"
5103 //if to is defined, load it
5105 // At this point, 'to' can be one of 3 things, a cached page element from
5106 // a history stack entry, an id, or site-relative/absolute URL. If 'to' is
5107 // an id, we need to resolve it against the documentBase, not the location.href,
5108 // since the hashchange could've been the result of a forward/backward navigation
5109 // that crosses from an external page/dialog to an internal page/dialog.
5110 to = !path.isPath( to ) ? ( path.makeUrlAbsolute( '#' + to, documentBase ) ) : to;
5112 // If we're about to go to an initial URL that contains a reference to a non-existent
5113 // internal page, go to the first page instead. We know that the initial hash refers to a
5114 // non-existent page, because the initial hash did not end up in the initial urlHistory entry
5115 if ( to === path.makeUrlAbsolute( '#' + urlHistory.initialDst, documentBase ) &&
5116 urlHistory.stack.length && urlHistory.stack[0].url !== urlHistory.initialDst.replace( dialogHashKey, "" ) ) {
5117 to = $.mobile.firstPage;
5120 $.mobile.changePage( to, changePageOptions );
5123 //there's no hash, go to the first page in the dom
5124 $.mobile.changePage( $.mobile.firstPage, changePageOptions );
5128 // TODO roll the logic here into the handleHashChange method
5129 $window.bind( "navigate", function( e, data ) {
5132 if ( e.originalEvent && e.originalEvent.isDefaultPrevented() ) {
5136 url = $.event.special.navigate.originalEventName.indexOf( "hashchange" ) > -1 ? data.state.hash : data.state.url;
5139 url = $.mobile.path.parseLocation().hash;
5142 if( !url || url === "#" || url.indexOf( "#" + $.mobile.path.uiStateKey ) === 0 ){
5143 url = location.href;
5146 $.mobile._handleHashChange( url, data.state );
5149 //set page min-heights to be device specific
5150 $.mobile.document.bind( "pageshow", $.mobile.resetActivePageHeight );
5151 $.mobile.window.bind( "throttledresize", $.mobile.resetActivePageHeight );
5153 };//navreadyDeferred done callback
5155 $( function() { domreadyDeferred.resolve(); } );
5157 $.when( domreadyDeferred, $.mobile.navreadyDeferred ).done( function() { $.mobile._registerInternalEvents(); } );
5161 * fallback transition for flip in non-3D supporting browsers (which tend to handle complex transitions poorly in general
5164 (function( $, window, undefined ) {
5166 $.mobile.transitionFallbacks.flip = "fade";
5170 * fallback transition for flow in non-3D supporting browsers (which tend to handle complex transitions poorly in general
5173 (function( $, window, undefined ) {
5175 $.mobile.transitionFallbacks.flow = "fade";
5179 * fallback transition for pop in non-3D supporting browsers (which tend to handle complex transitions poorly in general
5182 (function( $, window, undefined ) {
5184 $.mobile.transitionFallbacks.pop = "fade";
5188 * fallback transition for slide in non-3D supporting browsers (which tend to handle complex transitions poorly in general
5191 (function( $, window, undefined ) {
5193 // Use the simultaneous transitions handler for slide transitions
5194 $.mobile.transitionHandlers.slide = $.mobile.transitionHandlers.simultaneous;
5196 // Set the slide transitions's fallback to "fade"
5197 $.mobile.transitionFallbacks.slide = "fade";
5201 * fallback transition for slidedown in non-3D supporting browsers (which tend to handle complex transitions poorly in general
5204 (function( $, window, undefined ) {
5206 $.mobile.transitionFallbacks.slidedown = "fade";
5210 * fallback transition for slidefade in non-3D supporting browsers (which tend to handle complex transitions poorly in general
5213 (function( $, window, undefined ) {
5215 // Set the slide transitions's fallback to "fade"
5216 $.mobile.transitionFallbacks.slidefade = "fade";
5220 * fallback transition for slideup in non-3D supporting browsers (which tend to handle complex transitions poorly in general
5223 (function( $, window, undefined ) {
5225 $.mobile.transitionFallbacks.slideup = "fade";
5229 * fallback transition for turn in non-3D supporting browsers (which tend to handle complex transitions poorly in general
5232 (function( $, window, undefined ) {
5234 $.mobile.transitionFallbacks.turn = "fade";
5238 (function( $, undefined ) {
5240 $.mobile.page.prototype.options.degradeInputs = {
5244 "datetime-local": false,
5257 //auto self-init widgets
5258 $.mobile.document.bind( "pagecreate create", function( e ) {
5260 var page = $.mobile.closestPageData( $( e.target ) ), options;
5266 options = page.options;
5268 // degrade inputs to avoid poorly implemented native functionality
5269 $( e.target ).find( "input" ).not( page.keepNativeSelector() ).each(function() {
5270 var $this = $( this ),
5271 type = this.getAttribute( "type" ),
5272 optType = options.degradeInputs[ type ] || "text";
5274 if ( options.degradeInputs[ type ] ) {
5275 var html = $( "<div>" ).html( $this.clone() ).html(),
5276 // In IE browsers, the type sometimes doesn't exist in the cloned markup, so we replace the closing tag instead
5277 hasType = html.indexOf( " type=" ) > -1,
5278 findstr = hasType ? /\s+type=["']?\w+['"]?/ : /\/?>/,
5279 repstr = " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\"" + ( hasType ? "" : ">" );
5281 $this.replaceWith( html.replace( findstr, repstr ) );
5289 (function( $, window, undefined ) {
5291 $.widget( "mobile.dialog", $.mobile.widget, {
5294 closeBtnText: "Close",
5297 initSelector: ":jqmData(role='dialog')"
5300 // Override the theme set by the page plugin on pageshow
5301 _handlePageBeforeShow: function() {
5302 this._isCloseable = true;
5303 if ( this.options.overlayTheme ) {
5305 .page( "removeContainerBackground" )
5306 .page( "setContainerBackground", this.options.overlayTheme );
5310 _create: function() {
5313 cornerClass = !!this.options.corners ? " ui-corner-all" : "",
5314 dialogWrap = $( "<div/>", {
5316 "class" : "ui-dialog-contain ui-overlay-shadow" + cornerClass
5319 $el.addClass( "ui-dialog ui-overlay-" + this.options.overlayTheme );
5321 // Class the markup for dialog styling
5323 $el.wrapInner( dialogWrap );
5326 - clicks and submits should use the closing transition that the dialog opened with
5327 unless a data-transition is specified on the link/form
5328 - if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally
5330 $el.bind( "vclick submit", function( event ) {
5331 var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ),
5334 if ( $target.length && !$target.jqmData( "transition" ) ) {
5336 active = $.mobile.urlHistory.getActive() || {};
5338 $target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) )
5339 .attr( "data-" + $.mobile.ns + "direction", "reverse" );
5344 pagebeforeshow: "_handlePageBeforeShow"
5348 _createComplete: false
5351 this._setCloseBtn( this.options.closeBtn );
5354 _setCloseBtn: function( value ) {
5355 var self = this, btn, location;
5357 if ( this._headerCloseButton ) {
5358 this._headerCloseButton.remove();
5359 this._headerCloseButton = null;
5361 if ( value !== "none" ) {
5363 location = ( value === "left" ? "left" : "right" );
5364 btn = $( "<a href='#' class='ui-btn-" + location + "' data-" + $.mobile.ns + "icon='delete' data-" + $.mobile.ns + "iconpos='notext'>"+ this.options.closeBtnText + "</a>" );
5365 this.element.children().find( ":jqmData(role='header')" ).first().prepend( btn );
5366 if ( this._createComplete && $.fn.buttonMarkup ) {
5369 this._createComplete = true;
5371 // this must be an anonymous function so that select menu dialogs can replace
5372 // the close method. This is a change from previously just defining data-rel=back
5373 // on the button and letting nav handle it
5375 // Use click rather than vclick in order to prevent the possibility of unintentionally
5376 // reopening the dialog if the dialog opening item was directly under the close button.
5377 btn.bind( "click", function() {
5381 this._headerCloseButton = btn;
5385 _setOption: function( key, value ) {
5386 if ( key === "closeBtn" ) {
5387 this._setCloseBtn( value );
5389 this._super( key, value );
5392 // Close method goes back in history
5394 var idx, dst, hist = $.mobile.navigate.history;
5396 if ( this._isCloseable ) {
5397 this._isCloseable = false;
5398 // If the hash listening is enabled and there is at least one preceding history
5399 // entry it's ok to go back. Initial pages with the dialog hash state are an example
5400 // where the stack check is necessary
5401 if ( $.mobile.hashListeningEnabled && hist.activeIndex > 0 ) {
5404 idx = Math.max( 0, hist.activeIndex - 1 );
5405 dst = hist.stack[ idx ].pageUrl || hist.stack[ idx ].url;
5406 hist.previousIndex = hist.activeIndex;
5407 hist.activeIndex = idx;
5408 if ( !$.mobile.path.isPath( dst ) ) {
5409 dst = $.mobile.path.makeUrlAbsolute( "#" + dst );
5412 $.mobile.changePage( dst, { direction: "back", changeHash: false, fromHashChange: true } );
5418 //auto self-init widgets
5419 $.mobile.document.delegate( $.mobile.dialog.prototype.options.initSelector, "pagecreate", function() {
5420 $.mobile.dialog.prototype.enhance( this );
5425 (function( $, undefined ) {
5427 $.mobile.page.prototype.options.backBtnText = "Back";
5428 $.mobile.page.prototype.options.addBackBtn = false;
5429 $.mobile.page.prototype.options.backBtnTheme = null;
5430 $.mobile.page.prototype.options.headerTheme = "a";
5431 $.mobile.page.prototype.options.footerTheme = "a";
5432 $.mobile.page.prototype.options.contentTheme = null;
5434 // NOTE bind used to force this binding to run before the buttonMarkup binding
5435 // which expects .ui-footer top be applied in its gigantic selector
5436 // TODO remove the buttonMarkup giant selector and move it to the various modules
5437 // on which it depends
5438 $.mobile.document.bind( "pagecreate", function( e ) {
5439 var $page = $( e.target ),
5440 o = $page.data( "mobile-page" ).options,
5441 pageRole = $page.jqmData( "role" ),
5442 pageTheme = o.theme;
5444 $( ":jqmData(role='header'), :jqmData(role='footer'), :jqmData(role='content')", $page )
5448 var $this = $( this ),
5449 role = $this.jqmData( "role" ),
5450 theme = $this.jqmData( "theme" ),
5451 contentTheme = theme || o.contentTheme || ( pageRole === "dialog" && pageTheme ),
5457 $this.addClass( "ui-" + role );
5459 //apply theming and markup modifications to page,header,content,footer
5460 if ( role === "header" || role === "footer" ) {
5462 var thisTheme = theme || ( role === "header" ? o.headerTheme : o.footerTheme ) || pageTheme;
5466 .addClass( "ui-bar-" + thisTheme )
5468 .attr( "role", role === "header" ? "banner" : "contentinfo" );
5470 if ( role === "header") {
5471 // Right,left buttons
5472 $headeranchors = $this.children( "a, button" );
5473 leftbtn = $headeranchors.hasClass( "ui-btn-left" );
5474 rightbtn = $headeranchors.hasClass( "ui-btn-right" );
5476 leftbtn = leftbtn || $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length;
5478 rightbtn = rightbtn || $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length;
5481 // Auto-add back btn on pages beyond first view
5482 if ( o.addBackBtn &&
5483 role === "header" &&
5484 $( ".ui-page" ).length > 1 &&
5485 $page.jqmData( "url" ) !== $.mobile.path.stripHash( location.hash ) &&
5488 backBtn = $( "<a href='javascript:void(0);' class='ui-btn-left' data-"+ $.mobile.ns +"rel='back' data-"+ $.mobile.ns +"icon='arrow-l'>"+ o.backBtnText +"</a>" )
5489 // If theme is provided, override default inheritance
5490 .attr( "data-"+ $.mobile.ns +"theme", o.backBtnTheme || thisTheme )
5491 .prependTo( $this );
5495 $this.children( "h1, h2, h3, h4, h5, h6" )
5496 .addClass( "ui-title" )
5497 // Regardless of h element number in src, it becomes h1 for the enhanced page
5503 } else if ( role === "content" ) {
5504 if ( contentTheme ) {
5505 $this.addClass( "ui-body-" + ( contentTheme ) );
5509 $this.attr( "role", "main" );
5516 (function( $, undefined ) {
5518 // This function calls getAttribute, which should be safe for data-* attributes
5519 var getAttrFixed = function( e, key ) {
5520 var value = e.getAttribute( key );
5522 return value === "true" ? true :
5523 value === "false" ? false :
5524 value === null ? undefined : value;
5527 $.fn.buttonMarkup = function( options ) {
5528 var $workingSet = this,
5529 nsKey = "data-" + $.mobile.ns,
5532 // Enforce options to be of type string
5533 options = ( options && ( $.type( options ) === "object" ) )? options : {};
5534 for ( var i = 0; i < $workingSet.length; i++ ) {
5535 var el = $workingSet.eq( i ),
5537 o = $.extend( {}, $.fn.buttonMarkup.defaults, {
5538 icon: options.icon !== undefined ? options.icon : getAttrFixed( e, nsKey + "icon" ),
5539 iconpos: options.iconpos !== undefined ? options.iconpos : getAttrFixed( e, nsKey + "iconpos" ),
5540 theme: options.theme !== undefined ? options.theme : getAttrFixed( e, nsKey + "theme" ) || $.mobile.getInheritedTheme( el, "c" ),
5541 inline: options.inline !== undefined ? options.inline : getAttrFixed( e, nsKey + "inline" ),
5542 shadow: options.shadow !== undefined ? options.shadow : getAttrFixed( e, nsKey + "shadow" ),
5543 corners: options.corners !== undefined ? options.corners : getAttrFixed( e, nsKey + "corners" ),
5544 iconshadow: options.iconshadow !== undefined ? options.iconshadow : getAttrFixed( e, nsKey + "iconshadow" ),
5545 mini: options.mini !== undefined ? options.mini : getAttrFixed( e, nsKey + "mini" )
5549 innerClass = "ui-btn-inner",
5550 textClass = "ui-btn-text",
5551 buttonClass, iconClass,
5554 // Button inner markup
5561 if ( o[ key ] === undefined || o[ key ] === null ) {
5562 el.removeAttr( nsKey + key );
5564 e.setAttribute( nsKey + key, o[ key ] );
5568 if ( getAttrFixed( e, nsKey + "rel" ) === "popup" && el.attr( "href" ) ) {
5569 e.setAttribute( "aria-haspopup", true );
5570 e.setAttribute( "aria-owns", el.attr( "href" ) );
5573 // Check if this element is already enhanced
5574 buttonElements = $.data( ( ( e.tagName === "INPUT" || e.tagName === "BUTTON" ) ? e.parentNode : e ), "buttonElements" );
5576 if ( buttonElements ) {
5577 e = buttonElements.outer;
5579 buttonInner = buttonElements.inner;
5580 buttonText = buttonElements.text;
5581 // We will recreate this icon below
5582 $( buttonElements.icon ).remove();
5583 buttonElements.icon = null;
5584 hover = buttonElements.hover;
5585 state = buttonElements.state;
5588 buttonInner = document.createElement( o.wrapperEls );
5589 buttonText = document.createElement( o.wrapperEls );
5591 buttonIcon = o.icon ? document.createElement( "span" ) : null;
5593 if ( attachEvents && !buttonElements ) {
5597 // if not, try to find closest theme container
5599 o.theme = $.mobile.getInheritedTheme( el, "c" );
5602 buttonClass = "ui-btn ";
5603 buttonClass += ( hover ? "ui-btn-hover-" + o.theme : "" );
5604 buttonClass += ( state ? " ui-btn-" + state + "-" + o.theme : "" );
5605 buttonClass += o.shadow ? " ui-shadow" : "";
5606 buttonClass += o.corners ? " ui-btn-corner-all" : "";
5608 if ( o.mini !== undefined ) {
5609 // Used to control styling in headers/footers, where buttons default to `mini` style.
5610 buttonClass += o.mini === true ? " ui-mini" : " ui-fullsize";
5613 if ( o.inline !== undefined ) {
5614 // Used to control styling in headers/footers, where buttons default to `inline` style.
5615 buttonClass += o.inline === true ? " ui-btn-inline" : " ui-btn-block";
5619 o.icon = "ui-icon-" + o.icon;
5620 o.iconpos = o.iconpos || "left";
5622 iconClass = "ui-icon " + o.icon;
5624 if ( o.iconshadow ) {
5625 iconClass += " ui-icon-shadow";
5630 buttonClass += " ui-btn-icon-" + o.iconpos;
5632 if ( o.iconpos === "notext" && !el.attr( "title" ) ) {
5633 el.attr( "title", el.getEncodedText() );
5637 if ( buttonElements ) {
5638 el.removeClass( buttonElements.bcls || "" );
5640 el.removeClass( "ui-link" ).addClass( buttonClass );
5642 buttonInner.className = innerClass;
5643 buttonText.className = textClass;
5644 if ( !buttonElements ) {
5645 buttonInner.appendChild( buttonText );
5648 buttonIcon.className = iconClass;
5649 if ( !( buttonElements && buttonElements.icon ) ) {
5650 buttonIcon.innerHTML = " ";
5651 buttonInner.appendChild( buttonIcon );
5655 while ( e.firstChild && !buttonElements ) {
5656 buttonText.appendChild( e.firstChild );
5659 if ( !buttonElements ) {
5660 e.appendChild( buttonInner );
5663 // Assign a structure containing the elements of this button to the elements of this button. This
5664 // will allow us to recognize this as an already-enhanced button in future calls to buttonMarkup().
5670 inner : buttonInner,
5675 $.data( e, 'buttonElements', buttonElements );
5676 $.data( buttonInner, 'buttonElements', buttonElements );
5677 $.data( buttonText, 'buttonElements', buttonElements );
5679 $.data( buttonIcon, 'buttonElements', buttonElements );
5686 $.fn.buttonMarkup.defaults = {
5693 function closestEnabledButton( element ) {
5697 // Note that we check for typeof className below because the element we
5698 // handed could be in an SVG DOM where className on SVG elements is defined to
5699 // be of a different type (SVGAnimatedString). We only operate on HTML DOM
5700 // elements, so we look for plain "string".
5701 cname = ( typeof element.className === 'string' ) && ( element.className + ' ' );
5702 if ( cname && cname.indexOf( "ui-btn " ) > -1 && cname.indexOf( "ui-disabled " ) < 0 ) {
5706 element = element.parentNode;
5712 function updateButtonClass( $btn, classToRemove, classToAdd, hover, state ) {
5713 var buttonElements = $.data( $btn[ 0 ], "buttonElements" );
5714 $btn.removeClass( classToRemove ).addClass( classToAdd );
5715 if ( buttonElements ) {
5716 buttonElements.bcls = $( document.createElement( "div" ) )
5717 .addClass( buttonElements.bcls + " " + classToAdd )
5718 .removeClass( classToRemove )
5720 if ( hover !== undefined ) {
5721 buttonElements.hover = hover;
5723 buttonElements.state = state;
5727 var attachEvents = function() {
5728 var hoverDelay = $.mobile.buttonMarkup.hoverDelay, hov, foc;
5730 $.mobile.document.bind( {
5731 "vmousedown vmousecancel vmouseup vmouseover vmouseout focus blur scrollstart": function( event ) {
5733 $btn = $( closestEnabledButton( event.target ) ),
5734 isTouchEvent = event.originalEvent && /^touch/.test( event.originalEvent.type ),
5737 if ( $btn.length ) {
5738 theme = $btn.attr( "data-" + $.mobile.ns + "theme" );
5740 if ( evt === "vmousedown" ) {
5741 if ( isTouchEvent ) {
5742 // Use a short delay to determine if the user is scrolling before highlighting
5743 hov = setTimeout( function() {
5744 updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-down-" + theme, undefined, "down" );
5747 updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-down-" + theme, undefined, "down" );
5749 } else if ( evt === "vmousecancel" || evt === "vmouseup" ) {
5750 updateButtonClass( $btn, "ui-btn-down-" + theme, "ui-btn-up-" + theme, undefined, "up" );
5751 } else if ( evt === "vmouseover" || evt === "focus" ) {
5752 if ( isTouchEvent ) {
5753 // Use a short delay to determine if the user is scrolling before highlighting
5754 foc = setTimeout( function() {
5755 updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-hover-" + theme, true, "" );
5758 updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-hover-" + theme, true, "" );
5760 } else if ( evt === "vmouseout" || evt === "blur" || evt === "scrollstart" ) {
5761 updateButtonClass( $btn, "ui-btn-hover-" + theme + " ui-btn-down-" + theme, "ui-btn-up-" + theme, false, "up" );
5763 clearTimeout( hov );
5766 clearTimeout( foc );
5771 "focusin focus": function( event ) {
5772 $( closestEnabledButton( event.target ) ).addClass( $.mobile.focusClass );
5774 "focusout blur": function( event ) {
5775 $( closestEnabledButton( event.target ) ).removeClass( $.mobile.focusClass );
5779 attachEvents = null;
5782 //links in bars, or those with data-role become buttons
5783 //auto self-init widgets
5784 $.mobile.document.bind( "pagecreate create", function( e ) {
5786 $( ":jqmData(role='button'), .ui-bar > a, .ui-header > a, .ui-footer > a, .ui-bar > :jqmData(role='controlgroup') > a", e.target )
5788 .not( "button, input, .ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" )
5795 (function( $, undefined ) {
5797 $.widget( "mobile.collapsible", $.mobile.widget, {
5799 expandCueText: " click to expand contents",
5800 collapseCueText: " click to collapse contents",
5802 heading: "h1,h2,h3,h4,h5,h6,legend",
5803 collapsedIcon: "plus",
5804 expandedIcon: "minus",
5811 initSelector: ":jqmData(role='collapsible')"
5813 _create: function() {
5815 var $el = this.element,
5817 collapsible = $el.addClass( "ui-collapsible" ),
5818 collapsibleHeading = $el.children( o.heading ).first(),
5819 collapsibleContent = collapsible.wrapInner( "<div class='ui-collapsible-content'></div>" ).children( ".ui-collapsible-content" ),
5820 collapsibleSet = $el.closest( ":jqmData(role='collapsible-set')" ).addClass( "ui-collapsible-set" ),
5821 collapsibleClasses = "";
5823 // Replace collapsibleHeading if it's a legend
5824 if ( collapsibleHeading.is( "legend" ) ) {
5825 collapsibleHeading = $( "<div role='heading'>"+ collapsibleHeading.html() +"</div>" ).insertBefore( collapsibleHeading );
5826 collapsibleHeading.next().remove();
5829 // If we are in a collapsible set
5830 if ( collapsibleSet.length ) {
5831 // Inherit the theme from collapsible-set
5833 o.theme = collapsibleSet.jqmData( "theme" ) || $.mobile.getInheritedTheme( collapsibleSet, "c" );
5835 // Inherit the content-theme from collapsible-set
5836 if ( !o.contentTheme ) {
5837 o.contentTheme = collapsibleSet.jqmData( "content-theme" );
5840 // Get the preference for collapsed icon in the set, but override with data- attribute on the individual collapsible
5841 o.collapsedIcon = $el.jqmData( "collapsed-icon" ) || collapsibleSet.jqmData( "collapsed-icon" ) || o.collapsedIcon;
5843 // Get the preference for expanded icon in the set, but override with data- attribute on the individual collapsible
5844 o.expandedIcon = $el.jqmData( "expanded-icon" ) || collapsibleSet.jqmData( "expanded-icon" ) || o.expandedIcon;
5846 // Gets the preference icon position in the set, but override with data- attribute on the individual collapsible
5847 o.iconpos = $el.jqmData( "iconpos" ) || collapsibleSet.jqmData( "iconpos" ) || o.iconpos;
5849 // Inherit the preference for inset from collapsible-set or set the default value to ensure equalty within a set
5850 if ( collapsibleSet.jqmData( "inset" ) !== undefined ) {
5851 o.inset = collapsibleSet.jqmData( "inset" );
5855 // Set corners for individual collapsibles to false when in a collapsible-set
5857 // Gets the preference for mini in the set
5859 o.mini = collapsibleSet.jqmData( "mini" );
5862 // get inherited theme if not a set and no theme has been set
5864 o.theme = $.mobile.getInheritedTheme( $el, "c" );
5869 collapsibleClasses += " ui-collapsible-inset";
5870 if ( !!o.corners ) {
5871 collapsibleClasses += " ui-corner-all" ;
5874 if ( o.contentTheme ) {
5875 collapsibleClasses += " ui-collapsible-themed-content";
5876 collapsibleContent.addClass( "ui-body-" + o.contentTheme );
5878 if ( collapsibleClasses !== "" ) {
5879 collapsible.addClass( collapsibleClasses );
5883 //drop heading in before content
5884 .insertBefore( collapsibleContent )
5885 //modify markup & attributes
5886 .addClass( "ui-collapsible-heading" )
5887 .append( "<span class='ui-collapsible-heading-status'></span>" )
5888 .wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" )
5895 icon: o.collapsedIcon,
5902 .bind( "expand collapse", function( event ) {
5903 if ( !event.isDefaultPrevented() ) {
5904 var $this = $( this ),
5905 isCollapse = ( event.type === "collapse" );
5907 event.preventDefault();
5910 .toggleClass( "ui-collapsible-heading-collapsed", isCollapse )
5911 .find( ".ui-collapsible-heading-status" )
5912 .text( isCollapse ? o.expandCueText : o.collapseCueText )
5915 .toggleClass( "ui-icon-" + o.expandedIcon, !isCollapse )
5916 // logic or cause same icon for expanded/collapsed state would remove the ui-icon-class
5917 .toggleClass( "ui-icon-" + o.collapsedIcon, ( isCollapse || o.expandedIcon === o.collapsedIcon ) )
5919 .find( "a" ).first().removeClass( $.mobile.activeBtnClass );
5921 $this.toggleClass( "ui-collapsible-collapsed", isCollapse );
5922 collapsibleContent.toggleClass( "ui-collapsible-content-collapsed", isCollapse ).attr( "aria-hidden", isCollapse );
5924 collapsibleContent.trigger( "updatelayout" );
5927 .trigger( o.collapsed ? "collapse" : "expand" );
5930 .bind( "tap", function( event ) {
5931 collapsibleHeading.find( "a" ).first().addClass( $.mobile.activeBtnClass );
5933 .bind( "click", function( event ) {
5935 var type = collapsibleHeading.is( ".ui-collapsible-heading-collapsed" ) ? "expand" : "collapse";
5937 collapsible.trigger( type );
5939 event.preventDefault();
5940 event.stopPropagation();
5945 //auto self-init widgets
5946 $.mobile.document.bind( "pagecreate create", function( e ) {
5947 $.mobile.collapsible.prototype.enhanceWithin( e.target );
5952 (function( $, undefined ) {
5954 $.mobile.behaviors.addFirstLastClasses = {
5955 _getVisibles: function( $els, create ) {
5959 visibles = $els.not( ".ui-screen-hidden" );
5961 visibles = $els.filter( ":visible" );
5962 if ( visibles.length === 0 ) {
5963 visibles = $els.not( ".ui-screen-hidden" );
5970 _addFirstLastClasses: function( $els, $visibles, create ) {
5971 $els.removeClass( "ui-first-child ui-last-child" );
5972 $visibles.eq( 0 ).addClass( "ui-first-child" ).end().last().addClass( "ui-last-child" );
5974 this.element.trigger( "updatelayout" );
5981 (function( $, undefined ) {
5983 $.widget( "mobile.collapsibleset", $.mobile.widget, $.extend( {
5985 initSelector: ":jqmData(role='collapsible-set')"
5987 _create: function() {
5988 var $el = this.element.addClass( "ui-collapsible-set" ),
5991 // Inherit the theme from collapsible-set
5993 o.theme = $.mobile.getInheritedTheme( $el, "c" );
5995 // Inherit the content-theme from collapsible-set
5996 if ( !o.contentTheme ) {
5997 o.contentTheme = $el.jqmData( "content-theme" );
5999 // Inherit the corner styling from collapsible-set
6001 o.corners = $el.jqmData( "corners" );
6004 if ( $el.jqmData( "inset" ) !== undefined ) {
6005 o.inset = $el.jqmData( "inset" );
6007 o.inset = o.inset !== undefined ? o.inset : true;
6008 o.corners = o.corners !== undefined ? o.corners : true;
6010 if ( !!o.corners && !!o.inset ) {
6011 $el.addClass( "ui-corner-all" );
6014 // Initialize the collapsible set if it's not already initialized
6015 if ( !$el.jqmData( "collapsiblebound" ) ) {
6017 .jqmData( "collapsiblebound", true )
6018 .bind( "expand", function( event ) {
6019 var closestCollapsible = $( event.target )
6020 .closest( ".ui-collapsible" );
6021 if ( closestCollapsible.parent().is( ":jqmData(role='collapsible-set')" ) ) {
6023 .siblings( ".ui-collapsible" )
6024 .trigger( "collapse" );
6031 var $el = this.element,
6032 collapsiblesInSet = $el.children( ":jqmData(role='collapsible')" ),
6033 expanded = collapsiblesInSet.filter( ":jqmData(collapsed='false')" );
6034 this._refresh( "true" );
6036 // Because the corners are handled by the collapsible itself and the default state is collapsed
6037 // That was causing https://github.com/jquery/jquery-mobile/issues/4116
6038 expanded.trigger( "expand" );
6041 _refresh: function( create ) {
6042 var collapsiblesInSet = this.element.children( ":jqmData(role='collapsible')" );
6044 $.mobile.collapsible.prototype.enhance( collapsiblesInSet.not( ".ui-collapsible" ) );
6046 this._addFirstLastClasses( collapsiblesInSet, this._getVisibles( collapsiblesInSet, create ), create );
6049 refresh: function() {
6050 this._refresh( false );
6052 }, $.mobile.behaviors.addFirstLastClasses ) );
6054 //auto self-init widgets
6055 $.mobile.document.bind( "pagecreate create", function( e ) {
6056 $.mobile.collapsibleset.prototype.enhanceWithin( e.target );
6061 (function( $, undefined ) {
6063 // filter function removes whitespace between label and form element so we can use inline-block (nodeType 3 = text)
6064 $.fn.fieldcontain = function( options ) {
6066 .addClass( "ui-field-contain ui-body ui-br" )
6067 .contents().filter( function() {
6068 return ( this.nodeType === 3 && !/\S/.test( this.nodeValue ) );
6072 //auto self-init widgets
6073 $( document ).bind( "pagecreate create", function( e ) {
6074 $( ":jqmData(role='fieldcontain')", e.target ).jqmEnhanceable().fieldcontain();
6079 (function( $, undefined ) {
6081 $.fn.grid = function( options ) {
6082 return this.each(function() {
6084 var $this = $( this ),
6088 $kids = $this.children(),
6089 gridCols = { solo:1, a:2, b:3, c:4, d:5 },
6094 if ( $kids.length <= 5 ) {
6095 for ( var letter in gridCols ) {
6096 if ( gridCols[ letter ] === $kids.length ) {
6102 $this.addClass( "ui-grid-duo" );
6105 iterator = gridCols[grid];
6107 $this.addClass( "ui-grid-" + grid );
6109 $kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" );
6111 if ( iterator > 1 ) {
6112 $kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" );
6114 if ( iterator > 2 ) {
6115 $kids.filter( ":nth-child(" + iterator + "n+3)" ).addClass( "ui-block-c" );
6117 if ( iterator > 3 ) {
6118 $kids.filter( ":nth-child(" + iterator + "n+4)" ).addClass( "ui-block-d" );
6120 if ( iterator > 4 ) {
6121 $kids.filter( ":nth-child(" + iterator + "n+5)" ).addClass( "ui-block-e" );
6127 (function( $, undefined ) {
6129 $.widget( "mobile.navbar", $.mobile.widget, {
6133 initSelector: ":jqmData(role='navbar')"
6136 _create: function() {
6138 var $navbar = this.element,
6139 $navbtns = $navbar.find( "a" ),
6140 iconpos = $navbtns.filter( ":jqmData(icon)" ).length ?
6141 this.options.iconpos : undefined;
6143 $navbar.addClass( "ui-navbar ui-mini" )
6144 .attr( "role", "navigation" )
6147 .grid({ grid: this.options.grid });
6149 $navbtns.buttonMarkup({
6156 $navbar.delegate( "a", "vclick", function( event ) {
6157 // ui-btn-inner is returned as target
6158 var target = $( event.target ).is( "a" ) ? $( this ) : $( this ).parent( "a" );
6160 if ( !target.is( ".ui-disabled, .ui-btn-active" ) ) {
6161 $navbtns.removeClass( $.mobile.activeBtnClass );
6162 $( this ).addClass( $.mobile.activeBtnClass );
6164 // The code below is a workaround to fix #1181
6165 var activeBtn = $( this );
6167 $( document ).one( "pagehide", function() {
6168 activeBtn.removeClass( $.mobile.activeBtnClass );
6173 // Buttons in the navbar with ui-state-persist class should regain their active state before page show
6174 $navbar.closest( ".ui-page" ).bind( "pagebeforeshow", function() {
6175 $navbtns.filter( ".ui-state-persist" ).addClass( $.mobile.activeBtnClass );
6180 //auto self-init widgets
6181 $.mobile.document.bind( "pagecreate create", function( e ) {
6182 $.mobile.navbar.prototype.enhanceWithin( e.target );
6187 (function( $, undefined ) {
6189 //Keeps track of the number of lists per page UID
6190 //This allows support for multiple nested list in the same page
6191 //https://github.com/jquery/jquery-mobile/issues/1617
6192 var listCountPerPage = {};
6194 $.widget( "mobile.listview", $.mobile.widget, $.extend( {
6202 splitIcon: "arrow-r",
6207 initSelector: ":jqmData(role='listview')"
6210 _create: function() {
6212 listviewClasses = "";
6214 listviewClasses += t.options.inset ? " ui-listview-inset" : "";
6216 if ( !!t.options.inset ) {
6217 listviewClasses += t.options.corners ? " ui-corner-all" : "";
6218 listviewClasses += t.options.shadow ? " ui-shadow" : "";
6221 // create listview markup
6222 t.element.addClass(function( i, orig ) {
6223 return orig + " ui-listview" + listviewClasses;
6229 // This is a generic utility method for finding the first
6230 // node with a given nodeName. It uses basic DOM traversal
6231 // to be fast and is meant to be a substitute for simple
6232 // $.fn.closest() and $.fn.children() calls on a single
6233 // element. Note that callers must pass both the lowerCase
6234 // and upperCase version of the nodeName they are looking for.
6235 // The main reason for this is that this function will be
6236 // called many times and we want to avoid having to lowercase
6237 // the nodeName from the element every time to ensure we have
6238 // a match. Note that this function lives here for now, but may
6239 // be moved into $.mobile if other components need a similar method.
6240 _findFirstElementByTagName: function( ele, nextProp, lcName, ucName ) {
6242 dict[ lcName ] = dict[ ucName ] = true;
6244 if ( dict[ ele.nodeName ] ) {
6247 ele = ele[ nextProp ];
6251 _getChildrenByTagName: function( ele, lcName, ucName ) {
6254 dict[ lcName ] = dict[ ucName ] = true;
6255 ele = ele.firstChild;
6257 if ( dict[ ele.nodeName ] ) {
6258 results.push( ele );
6260 ele = ele.nextSibling;
6262 return $( results );
6265 _addThumbClasses: function( containers ) {
6266 var i, img, len = containers.length;
6267 for ( i = 0; i < len; i++ ) {
6268 img = $( this._findFirstElementByTagName( containers[ i ].firstChild, "nextSibling", "img", "IMG" ) );
6270 img.addClass( "ui-li-thumb" );
6271 $( this._findFirstElementByTagName( img[ 0 ].parentNode, "parentNode", "li", "LI" ) ).addClass( img.is( ".ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" );
6276 refresh: function( create ) {
6277 this.parentPage = this.element.closest( ".ui-page" );
6278 this._createSubPages();
6280 var o = this.options,
6281 $list = this.element,
6283 dividertheme = $list.jqmData( "dividertheme" ) || o.dividerTheme,
6284 listsplittheme = $list.jqmData( "splittheme" ),
6285 listspliticon = $list.jqmData( "spliticon" ),
6286 listicon = $list.jqmData( "icon" ),
6287 li = this._getChildrenByTagName( $list[ 0 ], "li", "LI" ),
6288 ol = !!$.nodeName( $list[ 0 ], "ol" ),
6289 jsCount = !$.support.cssPseudoElement,
6290 start = $list.attr( "start" ),
6292 item, itemClass, itemTheme,
6293 a, last, splittheme, counter, startCount, newStartCount, countParent, icon, imgParents, img, linkIcon;
6295 if ( ol && jsCount ) {
6296 $list.find( ".ui-li-dec" ).remove();
6300 // Check if a start attribute has been set while taking a value of 0 into account
6301 if ( start || start === 0 ) {
6303 startCount = parseInt( start , 10 ) - 1;
6304 $list.css( "counter-reset", "listnumbering " + startCount );
6306 counter = parseInt( start , 10 );
6308 } else if ( jsCount ) {
6314 o.theme = $.mobile.getInheritedTheme( this.element, "c" );
6317 for ( var pos = 0, numli = li.length; pos < numli; pos++ ) {
6318 item = li.eq( pos );
6319 itemClass = "ui-li";
6321 // If we're creating the element, we update it regardless
6322 if ( create || !item.hasClass( "ui-li" ) ) {
6323 itemTheme = item.jqmData( "theme" ) || o.theme;
6324 a = this._getChildrenByTagName( item[ 0 ], "a", "A" );
6325 var isDivider = ( item.jqmData( "role" ) === "list-divider" );
6327 if ( a.length && !isDivider ) {
6328 icon = item.jqmData( "icon" );
6335 icon: a.length > 1 || icon === false ? false : icon || listicon || o.icon,
6339 if ( ( icon !== false ) && ( a.length === 1 ) ) {
6340 item.addClass( "ui-li-has-arrow" );
6343 a.first().removeClass( "ui-link" ).addClass( "ui-link-inherit" );
6345 if ( a.length > 1 ) {
6346 itemClass += " ui-li-has-alt";
6349 splittheme = listsplittheme || last.jqmData( "theme" ) || o.splitTheme;
6350 linkIcon = last.jqmData( "icon" );
6352 last.appendTo( item )
6353 .attr( "title", $.trim(last.getEncodedText()) )
6354 .addClass( "ui-li-link-alt" )
6363 .find( ".ui-btn-inner" )
6365 $( document.createElement( "span" ) ).buttonMarkup({
6370 // link icon overrides list item icon overrides ul element overrides options
6371 icon: linkIcon || icon || listspliticon || o.splitIcon
6375 } else if ( isDivider ) {
6377 itemClass += " ui-li-divider ui-bar-" + ( item.jqmData( "theme" ) || dividertheme );
6378 item.attr( "role", "heading" );
6381 //reset counter when a divider heading is encountered
6382 if ( start || start === 0 ) {
6384 newStartCount = parseInt( start , 10 ) - 1;
6385 item.css( "counter-reset", "listnumbering " + newStartCount );
6387 counter = parseInt( start , 10 );
6389 } else if ( jsCount ) {
6395 itemClass += " ui-li-static ui-btn-up-" + itemTheme;
6399 if ( ol && jsCount && itemClass.indexOf( "ui-li-divider" ) < 0 ) {
6400 countParent = itemClass.indexOf( "ui-li-static" ) > 0 ? item : item.find( ".ui-link-inherit" );
6402 countParent.addClass( "ui-li-jsnumbering" )
6403 .prepend( "<span class='ui-li-dec'>" + ( counter++ ) + ". </span>" );
6406 // Instead of setting item class directly on the list item and its
6407 // btn-inner at this point in time, push the item into a dictionary
6408 // that tells us what class to set on it so we can do this after this
6409 // processing loop is finished.
6411 if ( !itemClassDict[ itemClass ] ) {
6412 itemClassDict[ itemClass ] = [];
6415 itemClassDict[ itemClass ].push( item[ 0 ] );
6418 // Set the appropriate listview item classes on each list item
6419 // and their btn-inner elements. The main reason we didn't do this
6420 // in the for-loop above is because we can eliminate per-item function overhead
6421 // by calling addClass() and children() once or twice afterwards. This
6422 // can give us a significant boost on platforms like WP7.5.
6424 for ( itemClass in itemClassDict ) {
6425 $( itemClassDict[ itemClass ] ).addClass( itemClass ).children( ".ui-btn-inner" ).addClass( itemClass );
6428 $list.find( "h1, h2, h3, h4, h5, h6" ).addClass( "ui-li-heading" )
6431 .find( "p, dl" ).addClass( "ui-li-desc" )
6434 .find( ".ui-li-aside" ).each(function() {
6435 var $this = $( this );
6436 $this.prependTo( $this.parent() ); //shift aside to front for css float
6440 .find( ".ui-li-count" ).each(function() {
6441 $( this ).closest( "li" ).addClass( "ui-li-has-count" );
6442 }).addClass( "ui-btn-up-" + ( $list.jqmData( "counttheme" ) || this.options.countTheme) + " ui-btn-corner-all" );
6444 // The idea here is to look at the first image in the list item
6445 // itself, and any .ui-link-inherit element it may contain, so we
6446 // can place the appropriate classes on the image and list item.
6447 // Note that we used to use something like:
6449 // li.find(">img:eq(0), .ui-link-inherit>img:eq(0)").each( ... );
6451 // But executing a find() like that on Windows Phone 7.5 took a
6452 // really long time. Walking things manually with the code below
6453 // allows the 400 listview item page to load in about 3 seconds as
6454 // opposed to 30 seconds.
6456 this._addThumbClasses( li );
6457 this._addThumbClasses( $list.find( ".ui-link-inherit" ) );
6459 this._addFirstLastClasses( li, this._getVisibles( li, create ), create );
6460 // autodividers binds to this to redraw dividers after the listview refresh
6461 this._trigger( "afterrefresh" );
6464 //create a string for ID/subpage url creation
6465 _idStringEscape: function( str ) {
6466 return str.replace(/[^a-zA-Z0-9]/g, '-');
6469 _createSubPages: function() {
6470 var parentList = this.element,
6471 parentPage = parentList.closest( ".ui-page" ),
6472 parentUrl = parentPage.jqmData( "url" ),
6473 parentId = parentUrl || parentPage[ 0 ][ $.expando ],
6474 parentListId = parentList.attr( "id" ),
6476 dns = "data-" + $.mobile.ns,
6478 persistentFooterID = parentPage.find( ":jqmData(role='footer')" ).jqmData( "id" ),
6481 if ( typeof listCountPerPage[ parentId ] === "undefined" ) {
6482 listCountPerPage[ parentId ] = -1;
6485 parentListId = parentListId || ++listCountPerPage[ parentId ];
6487 $( parentList.find( "li>ul, li>ol" ).toArray().reverse() ).each(function( i ) {
6490 listId = list.attr( "id" ) || parentListId + "-" + i,
6491 parent = list.parent(),
6492 nodeElsFull = $( list.prevAll().toArray().reverse() ),
6493 nodeEls = nodeElsFull.length ? nodeElsFull : $( "<span>" + $.trim(parent.contents()[ 0 ].nodeValue) + "</span>" ),
6494 title = nodeEls.first().getEncodedText(),//url limits to first 30 chars of text
6495 id = ( parentUrl || "" ) + "&" + $.mobile.subPageUrlKey + "=" + listId,
6496 theme = list.jqmData( "theme" ) || o.theme,
6497 countTheme = list.jqmData( "counttheme" ) || parentList.jqmData( "counttheme" ) || o.countTheme,
6500 //define hasSubPages for use in later removal
6503 newPage = list.detach()
6504 .wrap( "<div " + dns + "role='page' " + dns + "url='" + id + "' " + dns + "theme='" + theme + "' " + dns + "count-theme='" + countTheme + "'><div " + dns + "role='content'></div></div>" )
6506 .before( "<div " + dns + "role='header' " + dns + "theme='" + o.headerTheme + "'><div class='ui-title'>" + title + "</div></div>" )
6507 .after( persistentFooterID ? $( "<div " + dns + "role='footer' " + dns + "id='"+ persistentFooterID +"'>" ) : "" )
6509 .appendTo( $.mobile.pageContainer );
6513 anchor = parent.find( 'a:first' );
6515 if ( !anchor.length ) {
6516 anchor = $( "<a/>" ).html( nodeEls || title ).prependTo( parent.empty() );
6519 anchor.attr( "href", "#" + id );
6523 // on pagehide, remove any nested pages along with the parent page, as long as they aren't active
6524 // and aren't embedded
6526 parentPage.is( ":jqmData(external-page='true')" ) &&
6527 parentPage.data( "mobile-page" ).options.domCache === false ) {
6529 var newRemove = function( e, ui ) {
6530 var nextPage = ui.nextPage, npURL,
6531 prEvent = new $.Event( "pageremove" );
6533 if ( ui.nextPage ) {
6534 npURL = nextPage.jqmData( "url" );
6535 if ( npURL.indexOf( parentUrl + "&" + $.mobile.subPageUrlKey ) !== 0 ) {
6536 self.childPages().remove();
6537 parentPage.trigger( prEvent );
6538 if ( !prEvent.isDefaultPrevented() ) {
6539 parentPage.removeWithDependents();
6545 // unbind the original page remove and replace with our specialized version
6547 .unbind( "pagehide.remove" )
6548 .bind( "pagehide.remove", newRemove);
6552 // TODO sort out a better way to track sub pages of the listview this is brittle
6553 childPages: function() {
6554 var parentUrl = this.parentPage.jqmData( "url" );
6556 return $( ":jqmData(url^='"+ parentUrl + "&" + $.mobile.subPageUrlKey + "')" );
6558 }, $.mobile.behaviors.addFirstLastClasses ) );
6560 //auto self-init widgets
6561 $.mobile.document.bind( "pagecreate create", function( e ) {
6562 $.mobile.listview.prototype.enhanceWithin( e.target );
6568 var meta = $( "meta[name=viewport]" ),
6569 initialContent = meta.attr( "content" ),
6570 disabledZoom = initialContent + ",maximum-scale=1, user-scalable=no",
6571 enabledZoom = initialContent + ",maximum-scale=10, user-scalable=yes",
6572 disabledInitially = /(user-scalable[\s]*=[\s]*no)|(maximum-scale[\s]*=[\s]*1)[$,\s]/.test( initialContent );
6574 $.mobile.zoom = $.extend( {}, {
6575 enabled: !disabledInitially,
6577 disable: function( lock ) {
6578 if ( !disabledInitially && !$.mobile.zoom.locked ) {
6579 meta.attr( "content", disabledZoom );
6580 $.mobile.zoom.enabled = false;
6581 $.mobile.zoom.locked = lock || false;
6584 enable: function( unlock ) {
6585 if ( !disabledInitially && ( !$.mobile.zoom.locked || unlock === true ) ) {
6586 meta.attr( "content", enabledZoom );
6587 $.mobile.zoom.enabled = true;
6588 $.mobile.zoom.locked = false;
6591 restore: function() {
6592 if ( !disabledInitially ) {
6593 meta.attr( "content", initialContent );
6594 $.mobile.zoom.enabled = true;
6601 (function( $, undefined ) {
6603 $.widget( "mobile.textinput", $.mobile.widget, {
6607 // This option defaults to true on iOS devices.
6608 preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
6609 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]), input[type='file']",
6611 clearSearchButtonText: null, //deprecating for 1.3...
6612 clearBtnText: "clear text",
6616 _create: function() {
6619 input = this.element,
6621 theme = o.theme || $.mobile.getInheritedTheme( this.element, "c" ),
6622 themeclass = " ui-body-" + theme,
6623 miniclass = o.mini ? " ui-mini" : "",
6624 isSearch = input.is( "[type='search'], :jqmData(type='search')" ),
6627 clearBtnText = o.clearSearchButtonText || o.clearBtnText,
6628 clearBtnBlacklist = input.is( "textarea, :jqmData(type='range')" ),
6629 inputNeedsClearBtn = !!o.clearBtn && !clearBtnBlacklist,
6630 inputNeedsWrap = input.is( "input" ) && !input.is( ":jqmData(type='range')" );
6632 function toggleClear() {
6633 setTimeout( function() {
6634 clearbtn.toggleClass( "ui-input-clear-hidden", !input.val() );
6638 $( "label[for='" + input.attr( "id" ) + "']" ).addClass( "ui-input-text" );
6640 focusedEl = input.addClass( "ui-input-text ui-body-"+ theme );
6642 // XXX: Temporary workaround for issue 785 (Apple bug 8910589).
6643 // Turn off autocorrect and autocomplete on non-iOS 5 devices
6644 // since the popup they use can't be dismissed by the user. Note
6645 // that we test for the presence of the feature by looking for
6646 // the autocorrect property on the input element. We currently
6647 // have no test for iOS 5 or newer so we're temporarily using
6648 // the touchOverflow support flag for jQM 1.0. Yes, I feel dirty. - jblas
6649 if ( typeof input[0].autocorrect !== "undefined" && !$.support.touchOverflow ) {
6650 // Set the attribute instead of the property just in case there
6651 // is code that attempts to make modifications via HTML.
6652 input[0].setAttribute( "autocorrect", "off" );
6653 input[0].setAttribute( "autocomplete", "off" );
6656 //"search" and "text" input widgets
6658 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();
6659 } else if ( inputNeedsWrap ) {
6660 focusedEl = input.wrap( "<div class='ui-input-text ui-shadow-inset ui-corner-all ui-btn-shadow" + themeclass + miniclass + "'></div>" ).parent();
6663 if( inputNeedsClearBtn || isSearch ) {
6664 clearbtn = $( "<a href='#' class='ui-input-clear' title='" + clearBtnText + "'>" + clearBtnText + "</a>" )
6665 .bind( "click", function( event ) {
6669 .trigger( "change" );
6670 clearbtn.addClass( "ui-input-clear-hidden" );
6671 event.preventDefault();
6673 .appendTo( focusedEl )
6683 focusedEl.addClass( "ui-input-has-clear" );
6688 input.bind( "paste cut keyup input focus change blur", toggleClear );
6690 else if ( !inputNeedsWrap && !isSearch ) {
6691 input.addClass( "ui-corner-all ui-shadow-inset" + themeclass + miniclass );
6694 input.focus(function() {
6695 // In many situations, iOS will zoom into the input upon tap, this prevents that from happening
6696 if ( o.preventFocusZoom ) {
6697 $.mobile.zoom.disable( true );
6699 focusedEl.addClass( $.mobile.focusClass );
6702 focusedEl.removeClass( $.mobile.focusClass );
6703 if ( o.preventFocusZoom ) {
6704 $.mobile.zoom.enable( true );
6709 if ( input.is( "textarea" ) ) {
6710 var extraLineHeight = 15,
6711 keyupTimeoutBuffer = 100,
6714 this._keyup = function() {
6715 var scrollHeight = input[ 0 ].scrollHeight,
6716 clientHeight = input[ 0 ].clientHeight;
6718 if ( clientHeight < scrollHeight ) {
6719 var paddingTop = parseFloat( input.css( "padding-top" ) ),
6720 paddingBottom = parseFloat( input.css( "padding-bottom" ) ),
6721 paddingHeight = paddingTop + paddingBottom;
6723 input.height( scrollHeight - paddingHeight + extraLineHeight );
6727 input.on( "keyup change input paste", function() {
6728 clearTimeout( keyupTimeout );
6729 keyupTimeout = setTimeout( self._keyup, keyupTimeoutBuffer );
6732 // binding to pagechange here ensures that for pages loaded via
6733 // ajax the height is recalculated without user input
6734 this._on( true, $.mobile.document, { "pagechange": "_keyup" });
6736 // Issue 509: the browser is not providing scrollHeight properly until the styles load
6737 if ( $.trim( input.val() ) ) {
6738 // bind to the window load to make sure the height is calculated based on BOTH
6740 this._on( true, $.mobile.window, {"load": "_keyup"});
6743 if ( input.attr( "disabled" ) ) {
6748 disable: function() {
6750 isSearch = this.element.is( "[type='search'], :jqmData(type='search')" ),
6751 inputNeedsWrap = this.element.is( "input" ) && !this.element.is( ":jqmData(type='range')" ),
6752 parentNeedsDisabled = this.element.attr( "disabled", true ) && ( inputNeedsWrap || isSearch );
6754 if ( parentNeedsDisabled ) {
6755 $el = this.element.parent();
6759 $el.addClass( "ui-disabled" );
6760 return this._setOption( "disabled", true );
6763 enable: function() {
6765 isSearch = this.element.is( "[type='search'], :jqmData(type='search')" ),
6766 inputNeedsWrap = this.element.is( "input" ) && !this.element.is( ":jqmData(type='range')" ),
6767 parentNeedsEnabled = this.element.attr( "disabled", false ) && ( inputNeedsWrap || isSearch );
6769 if ( parentNeedsEnabled ) {
6770 $el = this.element.parent();
6774 $el.removeClass( "ui-disabled" );
6775 return this._setOption( "disabled", false );
6779 //auto self-init widgets
6780 $.mobile.document.bind( "pagecreate create", function( e ) {
6781 $.mobile.textinput.prototype.enhanceWithin( e.target, true );
6786 (function( $, undefined ) {
6788 $.mobile.listview.prototype.options.filter = false;
6789 $.mobile.listview.prototype.options.filterPlaceholder = "Filter items...";
6790 $.mobile.listview.prototype.options.filterTheme = "c";
6791 $.mobile.listview.prototype.options.filterReveal = false;
6792 // TODO rename callback/deprecate and default to the item itself as the first argument
6793 var defaultFilterCallback = function( text, searchValue, item ) {
6794 return text.toString().toLowerCase().indexOf( searchValue ) === -1;
6797 $.mobile.listview.prototype.options.filterCallback = defaultFilterCallback;
6799 $.mobile.document.delegate( "ul, ol", "listviewcreate", function() {
6800 var list = $( this ),
6801 listview = list.data( "mobile-listview" );
6803 if ( !listview || !listview.options.filter ) {
6807 if ( listview.options.filterReveal ) {
6808 list.children().addClass( "ui-screen-hidden" );
6811 var wrapper = $( "<form>", {
6812 "class": "ui-listview-filter ui-bar-" + listview.options.filterTheme,
6814 }).submit( function( e ) {
6818 onKeyUp = function( e ) {
6819 var $this = $( this ),
6820 val = this.value.toLowerCase(),
6822 li = list.children(),
6823 lastval = $this.jqmData( "lastval" ) + "",
6827 // Check if a custom filter callback applies
6828 isCustomFilterCallback = listview.options.filterCallback !== defaultFilterCallback;
6830 if ( lastval && lastval === val ) {
6831 // Execute the handler only once per value change
6835 listview._trigger( "beforefilter", "beforefilter", { input: this } );
6837 // Change val as lastval for next execution
6838 $this.jqmData( "lastval" , val );
6839 if ( isCustomFilterCallback || val.length < lastval.length || val.indexOf( lastval ) !== 0 ) {
6841 // Custom filter callback applies or removed chars or pasted something totally different, check all items
6842 listItems = list.children();
6845 // Only chars added, not removed, only use visible subset
6846 listItems = list.children( ":not(.ui-screen-hidden)" );
6848 if ( !listItems.length && listview.options.filterReveal ) {
6849 listItems = list.children( ".ui-screen-hidden" );
6855 // This handles hiding regular rows without the text we search for
6856 // and any list dividers without regular rows shown under it
6858 for ( var i = listItems.length - 1; i >= 0; i-- ) {
6859 item = $( listItems[ i ] );
6860 itemtext = item.jqmData( "filtertext" ) || item.text();
6862 if ( item.is( "li:jqmData(role=list-divider)" ) ) {
6864 item.toggleClass( "ui-filter-hidequeue" , !childItems );
6869 } else if ( listview.options.filterCallback( itemtext, val, item ) ) {
6872 item.toggleClass( "ui-filter-hidequeue" , true );
6875 // There's a shown item in the bucket
6880 // Show items, not marked to be hidden
6882 .filter( ":not(.ui-filter-hidequeue)" )
6883 .toggleClass( "ui-screen-hidden", false );
6885 // Hide items, marked to be hidden
6887 .filter( ".ui-filter-hidequeue" )
6888 .toggleClass( "ui-screen-hidden", true )
6889 .toggleClass( "ui-filter-hidequeue", false );
6893 //filtervalue is empty => show all
6894 listItems.toggleClass( "ui-screen-hidden", !!listview.options.filterReveal );
6896 listview._addFirstLastClasses( li, listview._getVisibles( li, false ), false );
6898 search = $( "<input>", {
6899 placeholder: listview.options.filterPlaceholder
6901 .attr( "data-" + $.mobile.ns + "type", "search" )
6902 .jqmData( "lastval", "" )
6903 .bind( "keyup change input", onKeyUp )
6904 .appendTo( wrapper )
6907 if ( listview.options.inset ) {
6908 wrapper.addClass( "ui-listview-filter-inset" );
6911 wrapper.bind( "submit", function() {
6914 .insertBefore( list );
6919 (function( $, undefined ) {
6921 $.mobile.listview.prototype.options.autodividers = false;
6922 $.mobile.listview.prototype.options.autodividersSelector = function( elt ) {
6923 // look for the text in the given element
6924 var text = $.trim( elt.text() ) || null;
6930 // create the text for the divider (first uppercased letter)
6931 text = text.slice( 0, 1 ).toUpperCase();
6936 $.mobile.document.delegate( "ul,ol", "listviewcreate", function() {
6938 var list = $( this ),
6939 listview = list.data( "mobile-listview" );
6941 if ( !listview || !listview.options.autodividers ) {
6945 var replaceDividers = function () {
6946 list.find( "li:jqmData(role='list-divider')" ).remove();
6948 var lis = list.find( 'li' ),
6949 lastDividerText = null, li, dividerText;
6951 for ( var i = 0; i < lis.length ; i++ ) {
6953 dividerText = listview.options.autodividersSelector( $( li ) );
6955 if ( dividerText && lastDividerText !== dividerText ) {
6956 var divider = document.createElement( 'li' );
6957 divider.appendChild( document.createTextNode( dividerText ) );
6958 divider.setAttribute( 'data-' + $.mobile.ns + 'role', 'list-divider' );
6959 li.parentNode.insertBefore( divider, li );
6962 lastDividerText = dividerText;
6966 var afterListviewRefresh = function () {
6967 list.unbind( 'listviewafterrefresh', afterListviewRefresh );
6970 list.bind( 'listviewafterrefresh', afterListviewRefresh );
6973 afterListviewRefresh();
6978 (function( $, undefined ) {
6980 $( document ).bind( "pagecreate create", function( e ) {
6981 $( ":jqmData(role='nojs')", e.target ).addClass( "ui-nojs" );
6987 (function( $, undefined ) {
6989 $.mobile.behaviors.formReset = {
6990 _handleFormReset: function() {
6991 this._on( this.element.closest( "form" ), {
6993 this._delay( "_reset" );
7002 * "checkboxradio" plugin
7005 (function( $, undefined ) {
7007 $.widget( "mobile.checkboxradio", $.mobile.widget, $.extend( {
7011 initSelector: "input[type='checkbox'],input[type='radio']"
7013 _create: function() {
7015 input = this.element,
7017 inheritAttr = function( input, dataAttr ) {
7018 return input.jqmData( dataAttr ) || input.closest( "form, fieldset" ).jqmData( dataAttr );
7020 // NOTE: Windows Phone could not find the label through a selector
7021 // filter works though.
7022 parentLabel = $( input ).closest( "label" ),
7023 label = parentLabel.length ? parentLabel : $( input ).closest( "form, fieldset, :jqmData(role='page'), :jqmData(role='dialog')" ).find( "label" ).filter( "[for='" + input[0].id + "']" ).first(),
7024 inputtype = input[0].type,
7025 mini = inheritAttr( input, "mini" ) || o.mini,
7026 checkedState = inputtype + "-on",
7027 uncheckedState = inputtype + "-off",
7028 iconpos = inheritAttr( input, "iconpos" ),
7029 checkedClass = "ui-" + checkedState,
7030 uncheckedClass = "ui-" + uncheckedState;
7032 if ( inputtype !== "checkbox" && inputtype !== "radio" ) {
7036 // Expose for other methods
7039 inputtype: inputtype,
7040 checkedClass: checkedClass,
7041 uncheckedClass: uncheckedClass,
7042 checkedicon: checkedState,
7043 uncheckedicon: uncheckedState
7046 // If there's no selected theme check the data attr
7048 o.theme = $.mobile.getInheritedTheme( this.element, "c" );
7051 label.buttonMarkup({
7053 icon: uncheckedState,
7059 // Wrap the input + label in a div
7060 var wrapper = document.createElement('div');
7061 wrapper.className = 'ui-' + inputtype;
7063 input.add( label ).wrapAll( wrapper );
7066 vmouseover: function( event ) {
7067 if ( $( this ).parent().is( ".ui-disabled" ) ) {
7068 event.stopPropagation();
7072 vclick: function( event ) {
7073 if ( input.is( ":disabled" ) ) {
7074 event.preventDefault();
7080 input.prop( "checked", inputtype === "radio" && true || !input.prop( "checked" ) );
7082 // trigger click handler's bound directly to the input as a substitute for
7083 // how label clicks behave normally in the browsers
7084 // TODO: it would be nice to let the browser's handle the clicks and pass them
7085 // through to the associate input. we can swallow that click at the parent
7086 // wrapper element level
7087 input.triggerHandler( 'click' );
7089 // Input set for common radio buttons will contain all the radio
7090 // buttons, but will not for checkboxes. clearing the checked status
7091 // of other radios ensures the active button state is applied properly
7092 self._getInputSet().not( input ).prop( "checked", false );
7101 vmousedown: function() {
7105 vclick: function() {
7106 var $this = $( this );
7108 // Adds checked attribute to checked input when keyboard is used
7109 if ( $this.is( ":checked" ) ) {
7111 $this.prop( "checked", true);
7112 self._getInputSet().not( $this ).prop( "checked", false );
7115 $this.prop( "checked", false );
7122 label.addClass( $.mobile.focusClass );
7126 label.removeClass( $.mobile.focusClass );
7130 this._handleFormReset();
7134 _cacheVals: function() {
7135 this._getInputSet().each(function() {
7136 $( this ).jqmData( "cacheVal", this.checked );
7140 //returns either a set of radios with the same name attribute, or a single checkbox
7141 _getInputSet: function() {
7142 if ( this.inputtype === "checkbox" ) {
7143 return this.element;
7146 return this.element.closest( "form, :jqmData(role='page'), :jqmData(role='dialog')" )
7147 .find( "input[name='" + this.element[0].name + "'][type='" + this.inputtype + "']" );
7150 _updateAll: function() {
7153 this._getInputSet().each(function() {
7154 var $this = $( this );
7156 if ( this.checked || self.inputtype === "checkbox" ) {
7157 $this.trigger( "change" );
7160 .checkboxradio( "refresh" );
7163 _reset: function() {
7167 refresh: function() {
7168 var input = this.element[ 0 ],
7169 active = " " + $.mobile.activeBtnClass,
7170 checkedClass = this.checkedClass + ( this.element.parents( ".ui-controlgroup-horizontal" ).length ? active : "" ),
7173 if ( input.checked ) {
7174 label.removeClass( this.uncheckedClass + active ).addClass( checkedClass ).buttonMarkup( { icon: this.checkedicon } );
7176 label.removeClass( checkedClass ).addClass( this.uncheckedClass ).buttonMarkup( { icon: this.uncheckedicon } );
7179 if ( input.disabled ) {
7186 disable: function() {
7187 this.element.prop( "disabled", true ).parent().addClass( "ui-disabled" );
7190 enable: function() {
7191 this.element.prop( "disabled", false ).parent().removeClass( "ui-disabled" );
7193 }, $.mobile.behaviors.formReset ) );
7195 //auto self-init widgets
7196 $.mobile.document.bind( "pagecreate create", function( e ) {
7197 $.mobile.checkboxradio.prototype.enhanceWithin( e.target, true );
7202 (function( $, undefined ) {
7204 $.widget( "mobile.button", $.mobile.widget, {
7214 initSelector: "button, [type='button'], [type='submit'], [type='reset']"
7216 _create: function() {
7217 var $el = this.element,
7219 // create a copy of this.options we can pass to buttonMarkup
7220 o = ( function( tdo ) {
7223 for ( key in tdo ) {
7224 if ( tdo[ key ] !== null && key !== "initSelector" ) {
7225 ret[ key ] = tdo[ key ];
7230 } )( this.options ),
7234 // if this is a link, check if it's been enhanced and, if not, use the right function
7235 if ( $el[ 0 ].tagName === "A" ) {
7236 if ( !$el.hasClass( "ui-btn" ) ) {
7242 // get the inherited theme
7243 // TODO centralize for all widgets
7244 if ( !this.options.theme ) {
7245 this.options.theme = $.mobile.getInheritedTheme( this.element, "c" );
7248 // 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
7249 /* if ( $el[0].className.length ) {
7250 classes = $el[0].className;
7252 if ( !!~$el[0].className.indexOf( "ui-btn-left" ) ) {
7253 classes = "ui-btn-left";
7256 if ( !!~$el[0].className.indexOf( "ui-btn-right" ) ) {
7257 classes = "ui-btn-right";
7260 if ( $el.attr( "type" ) === "submit" || $el.attr( "type" ) === "reset" ) {
7262 classes += " ui-submit";
7264 classes = "ui-submit";
7267 $( "label[for='" + $el.attr( "id" ) + "']" ).addClass( "ui-submit" );
7270 this.button = $( "<div></div>" )
7271 [ $el.html() ? "html" : "text" ]( $el.html() || $el.val() )
7272 .insertBefore( $el )
7274 .addClass( classes )
7275 .append( $el.addClass( "ui-btn-hidden" ) );
7277 $button = this.button;
7281 $button.addClass( $.mobile.focusClass );
7285 $button.removeClass( $.mobile.focusClass );
7292 _setOption: function( key, value ) {
7296 if ( key !== "initSelector" ) {
7297 this.button.buttonMarkup( op );
7298 // Record the option change in the options and in the DOM data-* attributes
7299 this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value );
7301 this._super( "_setOption", key, value );
7304 enable: function() {
7305 this.element.attr( "disabled", false );
7306 this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
7307 return this._setOption( "disabled", false );
7310 disable: function() {
7311 this.element.attr( "disabled", true );
7312 this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true );
7313 return this._setOption( "disabled", true );
7316 refresh: function() {
7317 var $el = this.element;
7319 if ( $el.prop("disabled") ) {
7325 // Grab the button's text element from its implementation-independent data item
7326 $( this.button.data( 'buttonElements' ).text )[ $el.html() ? "html" : "text" ]( $el.html() || $el.val() );
7330 //auto self-init widgets
7331 $.mobile.document.bind( "pagecreate create", function( e ) {
7332 $.mobile.button.prototype.enhanceWithin( e.target, true );
7337 (function( $, undefined ) {
7339 $.widget( "mobile.slider", $.mobile.widget, $.extend( {
7340 widgetEventPrefix: "slide",
7346 initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')",
7351 _create: function() {
7353 // TODO: Each of these should have comments explain what they're for
7355 control = this.element,
7356 parentTheme = $.mobile.getInheritedTheme( control, "c" ),
7357 theme = this.options.theme || parentTheme,
7358 trackTheme = this.options.trackTheme || parentTheme,
7359 cType = control[ 0 ].nodeName.toLowerCase(),
7360 isSelect = this.isToggleSwitch = cType === "select",
7361 isRangeslider = control.parent().is( ":jqmData(role='rangeslider')" ),
7362 selectClass = ( this.isToggleSwitch ) ? "ui-slider-switch" : "",
7363 controlID = control.attr( "id" ),
7364 $label = $( "[for='" + controlID + "']" ),
7365 labelID = $label.attr( "id" ) || controlID + "-label",
7366 label = $label.attr( "id", labelID ),
7367 min = !this.isToggleSwitch ? parseFloat( control.attr( "min" ) ) : 0,
7368 max = !this.isToggleSwitch ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1,
7369 step = window.parseFloat( control.attr( "step" ) || 1 ),
7370 miniClass = ( this.options.mini || control.jqmData( "mini" ) ) ? " ui-mini" : "",
7371 domHandle = document.createElement( "a" ),
7372 handle = $( domHandle ),
7373 domSlider = document.createElement( "div" ),
7374 slider = $( domSlider ),
7375 valuebg = this.options.highlight && !this.isToggleSwitch ? (function() {
7376 var bg = document.createElement( "div" );
7377 bg.className = "ui-slider-bg " + $.mobile.activeBtnClass + " ui-btn-corner-all";
7378 return $( bg ).prependTo( slider );
7383 domHandle.setAttribute( "href", "#" );
7384 domSlider.setAttribute( "role", "application" );
7385 domSlider.className = [this.isToggleSwitch ? "ui-slider " : "ui-slider-track ",selectClass," ui-btn-down-",trackTheme," ui-btn-corner-all", miniClass].join( "" );
7386 domHandle.className = "ui-slider-handle";
7387 domSlider.appendChild( domHandle );
7389 handle.buttonMarkup({ corners: true, theme: theme, shadow: true })
7392 "aria-valuemin": min,
7393 "aria-valuemax": max,
7394 "aria-valuenow": this._value(),
7395 "aria-valuetext": this._value(),
7396 "title": this._value(),
7397 "aria-labelledby": labelID
7408 isRangeslider: isRangeslider,
7411 userModified: false,
7415 if ( this.isToggleSwitch ) {
7416 wrapper = document.createElement( "div" );
7417 wrapper.className = "ui-slider-inneroffset";
7419 for ( var j = 0, length = domSlider.childNodes.length; j < length; j++ ) {
7420 wrapper.appendChild( domSlider.childNodes[j] );
7423 domSlider.appendChild( wrapper );
7425 // slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" );
7427 // make the handle move with a smooth transition
7428 handle.addClass( "ui-slider-handle-snapping" );
7430 options = control.find( "option" );
7432 for ( var i = 0, optionsCount = options.length; i < optionsCount; i++ ) {
7433 var side = !i ? "b" : "a",
7434 sliderTheme = !i ? " ui-btn-down-" + trackTheme : ( " " + $.mobile.activeBtnClass ),
7435 sliderLabel = document.createElement( "div" ),
7436 sliderImg = document.createElement( "span" );
7438 sliderImg.className = ["ui-slider-label ui-slider-label-", side, sliderTheme, " ui-btn-corner-all"].join( "" );
7439 sliderImg.setAttribute( "role", "img" );
7440 sliderImg.appendChild( document.createTextNode( options[i].innerHTML ) );
7441 $( sliderImg ).prependTo( slider );
7444 self._labels = $( ".ui-slider-label", slider );
7448 label.addClass( "ui-slider" );
7450 // monitor the input for updated values
7451 control.addClass( this.isToggleSwitch ? "ui-slider-switch" : "ui-slider-input" );
7453 this._on( control, {
7454 "change": "_controlChange",
7455 "keyup": "_controlKeyup",
7456 "blur": "_controlBlur",
7457 "vmouseup": "_controlVMouseUp"
7460 slider.bind( "vmousedown", $.proxy( this._sliderVMouseDown, this ) )
7461 .bind( "vclick", false );
7463 // We have to instantiate a new function object for the unbind to work properly
7464 // since the method itself is defined in the prototype (causing it to unbind everything)
7465 this._on( document, { "vmousemove": "_preventDocumentDrag" });
7466 this._on( slider.add( document ), { "vmouseup": "_sliderVMouseUp" });
7468 slider.insertAfter( control );
7470 // wrap in a div for styling purposes
7471 if ( !this.isToggleSwitch && !isRangeslider ) {
7472 wrapper = this.options.mini ? "<div class='ui-slider ui-mini'>" : "<div class='ui-slider'>";
7474 control.add( slider ).wrapAll( wrapper );
7477 // Only add focus class to toggle switch, sliders get it automatically from ui-btn
7478 if ( this.isToggleSwitch ) {
7481 slider.addClass( $.mobile.focusClass );
7485 slider.removeClass( $.mobile.focusClass );
7490 // bind the handle event callbacks and set the context to the widget instance
7491 this._on( this.handle, {
7492 "vmousedown": "_handleVMouseDown",
7493 "keydown": "_handleKeydown",
7494 "keyup": "_handleKeyup"
7497 this.handle.bind( "vclick", false );
7499 this._handleFormReset();
7501 this.refresh( undefined, undefined, true );
7504 _controlChange: function( event ) {
7505 // if the user dragged the handle, the "change" event was triggered from inside refresh(); don't call refresh() again
7506 if ( this._trigger( "controlchange", event ) === false ) {
7509 if ( !this.mouseMoved ) {
7510 this.refresh( this._value(), true );
7514 _controlKeyup: function( event ) { // necessary?
7515 this.refresh( this._value(), true, true );
7518 _controlBlur: function( event ) {
7519 this.refresh( this._value(), true );
7522 // it appears the clicking the up and down buttons in chrome on
7523 // range/number inputs doesn't trigger a change until the field is
7524 // blurred. Here we check thif the value has changed and refresh
7525 _controlVMouseUp: function( event ) {
7526 this._checkedRefresh();
7529 // NOTE force focus on handle
7530 _handleVMouseDown: function( event ) {
7531 this.handle.focus();
7534 _handleKeydown: function( event ) {
7535 var index = this._value();
7536 if ( this.options.disabled ) {
7540 // In all cases prevent the default and mark the handle as active
7541 switch ( event.keyCode ) {
7542 case $.mobile.keyCode.HOME:
7543 case $.mobile.keyCode.END:
7544 case $.mobile.keyCode.PAGE_UP:
7545 case $.mobile.keyCode.PAGE_DOWN:
7546 case $.mobile.keyCode.UP:
7547 case $.mobile.keyCode.RIGHT:
7548 case $.mobile.keyCode.DOWN:
7549 case $.mobile.keyCode.LEFT:
7550 event.preventDefault();
7552 if ( !this._keySliding ) {
7553 this._keySliding = true;
7554 this.handle.addClass( "ui-state-active" );
7560 // move the slider according to the keypress
7561 switch ( event.keyCode ) {
7562 case $.mobile.keyCode.HOME:
7563 this.refresh( this.min );
7565 case $.mobile.keyCode.END:
7566 this.refresh( this.max );
7568 case $.mobile.keyCode.PAGE_UP:
7569 case $.mobile.keyCode.UP:
7570 case $.mobile.keyCode.RIGHT:
7571 this.refresh( index + this.step );
7573 case $.mobile.keyCode.PAGE_DOWN:
7574 case $.mobile.keyCode.DOWN:
7575 case $.mobile.keyCode.LEFT:
7576 this.refresh( index - this.step );
7579 }, // remove active mark
7581 _handleKeyup: function( event ) {
7582 if ( this._keySliding ) {
7583 this._keySliding = false;
7584 this.handle.removeClass( "ui-state-active" );
7588 _sliderVMouseDown: function( event ) {
7589 // NOTE: we don't do this in refresh because we still want to
7590 // support programmatic alteration of disabled inputs
7591 if ( this.options.disabled || !( event.which === 1 || event.which === 0 ) ) {
7594 if ( this._trigger( "beforestart", event ) === false ) {
7597 this.dragging = true;
7598 this.userModified = false;
7599 this.mouseMoved = false;
7601 if ( this.isToggleSwitch ) {
7602 this.beforeStart = this.element[0].selectedIndex;
7606 this.refresh( event );
7607 this._trigger( "start" );
7611 _sliderVMouseUp: function() {
7612 if ( this.dragging ) {
7613 this.dragging = false;
7615 if ( this.isToggleSwitch ) {
7616 // make the handle move with a smooth transition
7617 this.handle.addClass( "ui-slider-handle-snapping" );
7619 if ( this.mouseMoved ) {
7620 // this is a drag, change the value only if user dragged enough
7621 if ( this.userModified ) {
7622 this.refresh( this.beforeStart === 0 ? 1 : 0 );
7624 this.refresh( this.beforeStart );
7627 // this is just a click, change the value
7628 this.refresh( this.beforeStart === 0 ? 1 : 0 );
7632 this.mouseMoved = false;
7633 this._trigger( "stop" );
7638 _preventDocumentDrag: function( event ) {
7639 // NOTE: we don't do this in refresh because we still want to
7640 // support programmatic alteration of disabled inputs
7641 if ( this._trigger( "drag", event ) === false) {
7644 if ( this.dragging && !this.options.disabled ) {
7646 // this.mouseMoved must be updated before refresh() because it will be used in the control "change" event
7647 this.mouseMoved = true;
7649 if ( this.isToggleSwitch ) {
7650 // make the handle move in sync with the mouse
7651 this.handle.removeClass( "ui-slider-handle-snapping" );
7654 this.refresh( event );
7656 // only after refresh() you can calculate this.userModified
7657 this.userModified = this.beforeStart !== this.element[0].selectedIndex;
7662 _checkedRefresh: function() {
7663 if ( this.value !== this._value() ) {
7664 this.refresh( this._value() );
7668 _value: function() {
7669 return this.isToggleSwitch ? this.element[0].selectedIndex : parseFloat( this.element.val() ) ;
7673 _reset: function() {
7674 this.refresh( undefined, false, true );
7677 refresh: function( val, isfromControl, preventInputUpdate ) {
7678 // NOTE: we don't return here because we want to support programmatic
7679 // alteration of the input value, which should still update the slider
7682 parentTheme = $.mobile.getInheritedTheme( this.element, "c" ),
7683 theme = this.options.theme || parentTheme,
7684 trackTheme = this.options.trackTheme || parentTheme,
7685 left, width, data, tol;
7687 self.slider[0].className = [ this.isToggleSwitch ? "ui-slider ui-slider-switch" : "ui-slider-track"," ui-btn-down-" + trackTheme,' ui-btn-corner-all', ( this.options.mini ) ? " ui-mini":""].join( "" );
7688 if ( this.options.disabled || this.element.attr( "disabled" ) ) {
7692 // set the stored value for comparison later
7693 this.value = this._value();
7694 if ( this.options.highlight && !this.isToggleSwitch && this.slider.find( ".ui-slider-bg" ).length === 0 ) {
7695 this.valuebg = (function() {
7696 var bg = document.createElement( "div" );
7697 bg.className = "ui-slider-bg " + $.mobile.activeBtnClass + " ui-btn-corner-all";
7698 return $( bg ).prependTo( self.slider );
7701 this.handle.buttonMarkup({ corners: true, theme: theme, shadow: true });
7703 var pxStep, percent,
7704 control = this.element,
7705 isInput = !this.isToggleSwitch,
7706 optionElements = isInput ? [] : control.find( "option" ),
7707 min = isInput ? parseFloat( control.attr( "min" ) ) : 0,
7708 max = isInput ? parseFloat( control.attr( "max" ) ) : optionElements.length - 1,
7709 step = ( isInput && parseFloat( control.attr( "step" ) ) > 0 ) ? parseFloat( control.attr( "step" ) ) : 1;
7711 if ( typeof val === "object" ) {
7713 // a slight tolerance helped get to the ends of the slider
7716 left = this.slider.offset().left;
7717 width = this.slider.width();
7718 pxStep = width/((max-min)/step);
7719 if ( !this.dragging ||
7720 data.pageX < left - tol ||
7721 data.pageX > left + width + tol ) {
7725 percent = ( ( data.pageX - left ) / width ) * 100;
7727 percent = Math.round( ( ( data.pageX - left ) / width ) * 100 );
7730 if ( val == null ) {
7731 val = isInput ? parseFloat( control.val() || 0 ) : control[0].selectedIndex;
7733 percent = ( parseFloat( val ) - min ) / ( max - min ) * 100;
7736 if ( isNaN( percent ) ) {
7740 var newval = ( percent / 100 ) * ( max - min ) + min;
7742 //from jQuery UI slider, the following source will round to the nearest step
7743 var valModStep = ( newval - min ) % step;
7744 var alignValue = newval - valModStep;
7746 if ( Math.abs( valModStep ) * 2 >= step ) {
7747 alignValue += ( valModStep > 0 ) ? step : ( -step );
7750 var percentPerStep = 100/((max-min)/step);
7751 // Since JavaScript has problems with large floats, round
7752 // the final value to 5 digits after the decimal point (see jQueryUI: #4124)
7753 newval = parseFloat( alignValue.toFixed(5) );
7755 if ( typeof pxStep === "undefined" ) {
7756 pxStep = width / ( (max-min) / step );
7758 if ( pxStep > 1 && isInput ) {
7759 percent = ( newval - min ) * percentPerStep * ( 1 / step );
7761 if ( percent < 0 ) {
7765 if ( percent > 100 ) {
7769 if ( newval < min ) {
7773 if ( newval > max ) {
7777 this.handle.css( "left", percent + "%" );
7779 this.handle[0].setAttribute( "aria-valuenow", isInput ? newval : optionElements.eq( newval ).attr( "value" ) );
7781 this.handle[0].setAttribute( "aria-valuetext", isInput ? newval : optionElements.eq( newval ).getEncodedText() );
7783 this.handle[0].setAttribute( "title", isInput ? newval : optionElements.eq( newval ).getEncodedText() );
7785 if ( this.valuebg ) {
7786 this.valuebg.css( "width", percent + "%" );
7789 // drag the label widths
7790 if ( this._labels ) {
7791 var handlePercent = this.handle.width() / this.slider.width() * 100,
7792 aPercent = percent && handlePercent + ( 100 - handlePercent ) * percent / 100,
7793 bPercent = percent === 100 ? 0 : Math.min( handlePercent + 100 - aPercent, 100 );
7795 this._labels.each(function() {
7796 var ab = $( this ).is( ".ui-slider-label-a" );
7797 $( this ).width( ( ab ? aPercent : bPercent ) + "%" );
7801 if ( !preventInputUpdate ) {
7802 var valueChanged = false;
7804 // update control"s value
7806 valueChanged = control.val() !== newval;
7807 control.val( newval );
7809 valueChanged = control[ 0 ].selectedIndex !== newval;
7810 control[ 0 ].selectedIndex = newval;
7812 if ( this._trigger( "beforechange", val ) === false) {
7815 if ( !isfromControl && valueChanged ) {
7816 control.trigger( "change" );
7821 enable: function() {
7822 this.element.attr( "disabled", false );
7823 this.slider.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
7824 return this._setOption( "disabled", false );
7827 disable: function() {
7828 this.element.attr( "disabled", true );
7829 this.slider.addClass( "ui-disabled" ).attr( "aria-disabled", true );
7830 return this._setOption( "disabled", true );
7833 }, $.mobile.behaviors.formReset ) );
7835 //auto self-init widgets
7836 $.mobile.document.bind( "pagecreate create", function( e ) {
7837 $.mobile.slider.prototype.enhanceWithin( e.target, true );
7842 (function( $, undefined ) {
7843 $.widget( "mobile.rangeslider", $.mobile.widget, {
7849 initSelector: ":jqmData(role='rangeslider')",
7854 _create: function() {
7857 elClass = this.options.mini ? "ui-rangeslider ui-mini" : "ui-rangeslider",
7858 _inputFirst = $el.find( "input" ).first(),
7859 _inputLast = $el.find( "input" ).last(),
7860 label = $el.find( "label" ).first(),
7861 _sliderFirst = $.data( _inputFirst.get(0), "mobileSlider" ).slider,
7862 _sliderLast = $.data( _inputLast.get(0), "mobileSlider" ).slider,
7863 firstHandle = $.data( _inputFirst.get(0), "mobileSlider" ).handle,
7864 _sliders = $( "<div class=\"ui-rangeslider-sliders\" />" ).appendTo( $el );
7866 if ( $el.find( "label" ).length > 1 ) {
7867 secondLabel = $el.find( "label" ).last().hide();
7870 _inputFirst.addClass( "ui-rangeslider-first" );
7871 _inputLast.addClass( "ui-rangeslider-last" );
7872 $el.addClass( elClass );
7874 _sliderFirst.appendTo( _sliders );
7875 _sliderLast.appendTo( _sliders );
7876 label.prependTo( $el );
7877 firstHandle.prependTo( _sliderLast );
7880 _inputFirst: _inputFirst,
7881 _inputLast: _inputLast,
7882 _sliderFirst: _sliderFirst,
7883 _sliderLast: _sliderLast,
7885 _sliderTarget: false,
7891 this._on( this.element.find( "input.ui-slider-input" ), {
7892 "slidebeforestart": "_slidebeforestart",
7893 "slidestop": "_slidestop",
7894 "slidedrag": "_slidedrag",
7895 "slidebeforechange": "_change",
7900 "mousedown":"_change"
7902 this._on( this.element.closest( "form" ), {
7903 "reset":"_handleReset"
7905 this._on( firstHandle, {
7906 "vmousedown": "_dragFirstHandle"
7909 _handleReset: function(){
7911 //we must wait for the stack to unwind before updateing other wise sliders will not have updated yet
7912 setTimeout( function(){
7913 self._updateHighlight();
7917 _dragFirstHandle: function( event ) {
7918 //if the first handle is dragged send the event to the first slider
7919 $.data( this._inputFirst.get(0), "mobileSlider" ).dragging = true;
7920 $.data( this._inputFirst.get(0), "mobileSlider" ).refresh( event );
7924 _slidedrag: function( event ) {
7925 var first = $( event.target ).is( this._inputFirst ),
7926 otherSlider = ( first ) ? this._inputLast : this._inputFirst;
7928 this._sliderTarget = false;
7929 //if the drag was initiated on an extreme and the other handle is focused send the events to
7930 //the closest handle
7931 if ( ( this._proxy === "first" && first ) || ( this._proxy === "last" && !first ) ) {
7932 $.data( otherSlider.get(0), "mobileSlider" ).dragging = true;
7933 $.data( otherSlider.get(0), "mobileSlider" ).refresh( event );
7938 _slidestop: function( event ) {
7939 var first = $( event.target ).is( this._inputFirst );
7941 this._proxy = false;
7942 //this stops dragging of the handle and brings the active track to the front
7943 //this makes clicks on the track go the the last handle used
7944 this.element.find( "input" ).trigger( "vmouseup" );
7945 this._sliderFirst.css( "z-index", first ? 1 : "" );
7948 _slidebeforestart: function( event ) {
7949 this._sliderTarget = false;
7950 //if the track is the target remember this and the original value
7951 if ( $( event.originalEvent.target ).hasClass( "ui-slider-track" ) ) {
7952 this._sliderTarget = true;
7953 this._targetVal = $( event.target ).val();
7957 _setOption: function( options ) {
7958 this._superApply( options );
7962 refresh: function() {
7963 var $el = this.element,
7966 $el.find( "input" ).slider({
7968 trackTheme: o.trackTheme,
7969 disabled: o.disabled,
7971 highlight: o.highlight
7972 }).slider( "refresh" );
7973 this._updateHighlight();
7976 _change: function( event ) {
7977 if ( event.type === "keyup" ) {
7978 this._updateHighlight();
7983 min = parseFloat( this._inputFirst.val(), 10 ),
7984 max = parseFloat( this._inputLast.val(), 10 ),
7985 first = $( event.target ).hasClass( "ui-rangeslider-first" ),
7986 thisSlider = first ? this._inputFirst : this._inputLast,
7987 otherSlider = first ? this._inputLast : this._inputFirst;
7990 if( ( this._inputFirst.val() > this._inputLast.val() && event.type === "mousedown" && !$(event.target).hasClass("ui-slider-handle")) ){
7992 } else if( event.type === "mousedown" ){
7995 if ( min > max && !this._sliderTarget ) {
7996 //this prevents min from being greater then max
7997 thisSlider.val( first ? max: min ).slider( "refresh" );
7998 this._trigger( "normalize" );
7999 } else if ( min > max ) {
8000 //this makes it so clicks on the target on either extreme go to the closest handle
8001 thisSlider.val( this._targetVal ).slider( "refresh" );
8003 //You must wait for the stack to unwind so first slider is updated before updating second
8004 setTimeout( function() {
8005 otherSlider.val( first ? min: max ).slider( "refresh" );
8006 $.data( otherSlider.get(0), "mobileSlider" ).handle.focus();
8007 self._sliderFirst.css( "z-index", first ? "" : 1 );
8008 self._trigger( "normalize" );
8010 this._proxy = ( first ) ? "first" : "last";
8012 //fixes issue where when both _sliders are at min they cannot be adjusted
8013 if ( min === max ) {
8014 $.data( thisSlider.get(0), "mobileSlider" ).handle.css( "z-index", 1 );
8015 $.data( otherSlider.get(0), "mobileSlider" ).handle.css( "z-index", 0 );
8017 $.data( otherSlider.get(0), "mobileSlider" ).handle.css( "z-index", "" );
8018 $.data( thisSlider.get(0), "mobileSlider" ).handle.css( "z-index", "" );
8021 this._updateHighlight();
8028 _updateHighlight: function() {
8029 var min = parseInt( $.data( this._inputFirst.get(0), "mobileSlider" ).handle.get(0).style.left, 10 ),
8030 max = parseInt( $.data( this._inputLast.get(0), "mobileSlider" ).handle.get(0).style.left, 10 ),
8031 width = (max - min);
8033 this.element.find( ".ui-slider-bg" ).css({
8034 "margin-left": min + "%",
8035 "width": width + "%"
8039 _destroy: function() {
8040 this.element.removeClass( "ui-rangeslider ui-mini" ).find( "label" ).show();
8041 this._inputFirst.after( this._sliderFirst );
8042 this._inputLast.after( this._sliderLast );
8043 this._sliders.remove();
8044 this.element.find( "input" ).removeClass( "ui-rangeslider-first ui-rangeslider-last" ).slider( "destroy" );
8049 $.widget( "mobile.rangeslider", $.mobile.rangeslider, $.mobile.behaviors.formReset );
8051 //auto self-init widgets
8052 $( document ).bind( "pagecreate create", function( e ) {
8053 $.mobile.rangeslider.prototype.enhanceWithin( e.target, true );
8058 (function( $, undefined ) {
8060 $.widget( "mobile.selectmenu", $.mobile.widget, $.extend( {
8072 hidePlaceholderMenuItems: true,
8075 // This option defaults to true on iOS devices.
8076 preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
8077 initSelector: "select:not( :jqmData(role='slider') )",
8081 _button: function() {
8082 return $( "<div/>" );
8085 _setDisabled: function( value ) {
8086 this.element.attr( "disabled", value );
8087 this.button.attr( "aria-disabled", value );
8088 return this._setOption( "disabled", value );
8091 _focusButton : function() {
8094 setTimeout( function() {
8095 self.button.focus();
8099 _selectOptions: function() {
8100 return this.select.find( "option" );
8103 // setup items that are generally necessary for select menu extension
8104 _preExtension: function() {
8106 // 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
8107 /* if ( $el[0].className.length ) {
8108 classes = $el[0].className;
8110 if ( !!~this.element[0].className.indexOf( "ui-btn-left" ) ) {
8111 classes = " ui-btn-left";
8114 if ( !!~this.element[0].className.indexOf( "ui-btn-right" ) ) {
8115 classes = " ui-btn-right";
8118 this.select = this.element.removeClass( "ui-btn-left ui-btn-right" ).wrap( "<div class='ui-select" + classes + "'>" );
8119 this.selectID = this.select.attr( "id" );
8120 this.label = $( "label[for='"+ this.selectID +"']" ).addClass( "ui-select" );
8121 this.isMultiple = this.select[ 0 ].multiple;
8122 if ( !this.options.theme ) {
8123 this.options.theme = $.mobile.getInheritedTheme( this.select, "c" );
8127 _destroy: function() {
8128 var wrapper = this.element.parents( ".ui-select" );
8129 if ( wrapper.length > 0 ) {
8130 if ( wrapper.is( ".ui-btn-left, .ui-btn-right" ) ) {
8131 this.element.addClass( wrapper.is( ".ui-btn-left" ) ? "ui-btn-left" : "ui-btn-right" );
8133 this.element.insertAfter( wrapper );
8138 _create: function() {
8139 this._preExtension();
8141 // Allows for extension of the native select for custom selects and other plugins
8142 // see select.custom for example extension
8143 // TODO explore plugin registration
8144 this._trigger( "beforeCreate" );
8146 this.button = this._button();
8150 options = this.options,
8152 inline = options.inline || this.select.jqmData( "inline" ),
8153 mini = options.mini || this.select.jqmData( "mini" ),
8154 iconpos = options.icon ? ( options.iconpos || this.select.jqmData( "iconpos" ) ) : false,
8156 // IE throws an exception at options.item() function when
8157 // there is no selected item
8158 // select first in this case
8159 selectedIndex = this.select[ 0 ].selectedIndex === -1 ? 0 : this.select[ 0 ].selectedIndex,
8161 // TODO values buttonId and menuId are undefined here
8162 button = this.button
8163 .insertBefore( this.select )
8165 theme: options.theme,
8169 corners: options.corners,
8170 shadow: options.shadow,
8171 iconshadow: options.iconshadow,
8175 this.setButtonText();
8177 // Opera does not properly support opacity on select elements
8178 // In Mini, it hides the element, but not its text
8179 // On the desktop,it seems to do the opposite
8180 // for these reasons, using the nativeMenu option results in a full native select in Opera
8181 if ( options.nativeMenu && window.opera && window.opera.version ) {
8182 button.addClass( "ui-select-nativeonly" );
8185 // Add counter for multi selects
8186 if ( this.isMultiple ) {
8187 this.buttonCount = $( "<span>" )
8188 .addClass( "ui-li-count ui-btn-up-c ui-btn-corner-all" )
8190 .appendTo( button.addClass('ui-li-has-count') );
8193 // Disable if specified
8194 if ( options.disabled || this.element.attr('disabled')) {
8198 // Events on native select
8199 this.select.change(function() {
8202 if ( !!options.nativeMenu ) {
8207 this._handleFormReset();
8216 .appendTo( self.button )
8217 .bind( "vmousedown", function() {
8218 // Add active class to button
8219 self.button.addClass( $.mobile.activeBtnClass );
8221 .bind( "focus", function() {
8222 self.button.addClass( $.mobile.focusClass );
8224 .bind( "blur", function() {
8225 self.button.removeClass( $.mobile.focusClass );
8227 .bind( "focus vmouseover", function() {
8228 self.button.trigger( "vmouseover" );
8230 .bind( "vmousemove", function() {
8231 // Remove active class on scroll/touchmove
8232 self.button.removeClass( $.mobile.activeBtnClass );
8234 .bind( "change blur vmouseout", function() {
8235 self.button.trigger( "vmouseout" )
8236 .removeClass( $.mobile.activeBtnClass );
8238 .bind( "change blur", function() {
8239 self.button.removeClass( "ui-btn-down-" + self.options.theme );
8242 // In many situations, iOS will zoom into the select upon tap, this prevents that from happening
8243 self.button.bind( "vmousedown", function() {
8244 if ( self.options.preventFocusZoom ) {
8245 $.mobile.zoom.disable( true );
8248 self.label.bind( "click focus", function() {
8249 if ( self.options.preventFocusZoom ) {
8250 $.mobile.zoom.disable( true );
8253 self.select.bind( "focus", function() {
8254 if ( self.options.preventFocusZoom ) {
8255 $.mobile.zoom.disable( true );
8258 self.button.bind( "mouseup", function() {
8259 if ( self.options.preventFocusZoom ) {
8260 setTimeout(function() {
8261 $.mobile.zoom.enable( true );
8265 self.select.bind( "blur", function() {
8266 if ( self.options.preventFocusZoom ) {
8267 $.mobile.zoom.enable( true );
8273 selected: function() {
8274 return this._selectOptions().filter( ":selected" );
8277 selectedIndices: function() {
8280 return this.selected().map(function() {
8281 return self._selectOptions().index( this );
8285 setButtonText: function() {
8287 selected = this.selected(),
8288 text = this.placeholder,
8289 span = $( document.createElement( "span" ) );
8291 this.button.find( ".ui-btn-text" ).html(function() {
8292 if ( selected.length ) {
8293 text = selected.map(function() {
8294 return $( this ).text();
8295 }).get().join( ", " );
8297 text = self.placeholder;
8300 // TODO possibly aggregate multiple select option classes
8301 return span.text( text )
8302 .addClass( self.select.attr( "class" ) )
8303 .addClass( selected.attr( "class" ) );
8307 setButtonCount: function() {
8308 var selected = this.selected();
8310 // multiple count inside button
8311 if ( this.isMultiple ) {
8312 this.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length );
8316 _reset: function() {
8320 refresh: function() {
8321 this.setButtonText();
8322 this.setButtonCount();
8325 // open and close preserved in native selects
8326 // to simplify users code when looping over selects
8330 disable: function() {
8331 this._setDisabled( true );
8332 this.button.addClass( "ui-disabled" );
8335 enable: function() {
8336 this._setDisabled( false );
8337 this.button.removeClass( "ui-disabled" );
8339 }, $.mobile.behaviors.formReset ) );
8341 //auto self-init widgets
8342 $.mobile.document.bind( "pagecreate create", function( e ) {
8343 $.mobile.selectmenu.prototype.enhanceWithin( e.target, true );
8347 (function( $, undefined ) {
8349 function fitSegmentInsideSegment( winSize, segSize, offset, desired ) {
8352 if ( winSize < segSize ) {
8353 // Center segment if it's bigger than the window
8354 ret = offset + ( winSize - segSize ) / 2;
8356 // Otherwise center it at the desired coordinate while keeping it completely inside the window
8357 ret = Math.min( Math.max( offset, desired - segSize / 2 ), offset + winSize - segSize );
8363 function windowCoords() {
8364 var $win = $.mobile.window;
8367 x: $win.scrollLeft(),
8368 y: $win.scrollTop(),
8369 cx: ( window.innerWidth || $win.width() ),
8370 cy: ( window.innerHeight || $win.height() )
8374 $.widget( "mobile.popup", $.mobile.widget, {
8381 positionTo: "origin",
8383 initSelector: ":jqmData(role='popup')",
8384 closeLinkSelector: "a:jqmData(rel='back')",
8385 closeLinkEvents: "click.popup",
8386 navigateEvents: "navigate.popup",
8387 closeEvents: "navigate.popup pagebeforechange.popup",
8390 // NOTE Windows Phone 7 has a scroll position caching issue that
8391 // requires us to disable popup history management by default
8392 // https://github.com/jquery/jquery-mobile/issues/4784
8394 // NOTE this option is modified in _create!
8395 history: !$.mobile.browser.oldIE
8398 _eatEventAndClose: function( e ) {
8400 e.stopImmediatePropagation();
8401 if ( this.options.dismissible ) {
8407 // Make sure the screen size is increased beyond the page height if the popup's causes the document to increase in height
8408 _resizeScreen: function() {
8409 var popupHeight = this._ui.container.outerHeight( true );
8411 this._ui.screen.removeAttr( "style" );
8412 if ( popupHeight > this._ui.screen.height() ) {
8413 this._ui.screen.height( popupHeight );
8417 _handleWindowKeyUp: function( e ) {
8418 if ( this._isOpen && e.keyCode === $.mobile.keyCode.ESCAPE ) {
8419 return this._eatEventAndClose( e );
8423 _expectResizeEvent: function() {
8424 var winCoords = windowCoords();
8426 if ( this._resizeData ) {
8427 if ( winCoords.x === this._resizeData.winCoords.x &&
8428 winCoords.y === this._resizeData.winCoords.y &&
8429 winCoords.cx === this._resizeData.winCoords.cx &&
8430 winCoords.cy === this._resizeData.winCoords.cy ) {
8431 // timeout not refreshed
8434 // clear existing timeout - it will be refreshed below
8435 clearTimeout( this._resizeData.timeoutId );
8439 this._resizeData = {
8440 timeoutId: setTimeout( $.proxy( this, "_resizeTimeout" ), 200 ),
8441 winCoords: winCoords
8447 _resizeTimeout: function() {
8448 if ( this._isOpen ) {
8449 if ( !this._expectResizeEvent() ) {
8450 if ( this._ui.container.hasClass( "ui-popup-hidden" ) ) {
8451 // effectively rapid-open the popup while leaving the screen intact
8452 this._ui.container.removeClass( "ui-popup-hidden" );
8453 this.reposition( { positionTo: "window" } );
8454 this._ignoreResizeEvents();
8457 this._resizeScreen();
8458 this._resizeData = null;
8459 this._orientationchangeInProgress = false;
8462 this._resizeData = null;
8463 this._orientationchangeInProgress = false;
8467 _ignoreResizeEvents: function() {
8470 if ( this._ignoreResizeTo ) {
8471 clearTimeout( this._ignoreResizeTo );
8473 this._ignoreResizeTo = setTimeout( function() { self._ignoreResizeTo = 0; }, 1000 );
8476 _handleWindowResize: function( e ) {
8477 if ( this._isOpen && this._ignoreResizeTo === 0 ) {
8478 if ( ( this._expectResizeEvent() || this._orientationchangeInProgress ) &&
8479 !this._ui.container.hasClass( "ui-popup-hidden" ) ) {
8480 // effectively rapid-close the popup while leaving the screen intact
8482 .addClass( "ui-popup-hidden" )
8483 .removeAttr( "style" );
8488 _handleWindowOrientationchange: function( e ) {
8489 if ( !this._orientationchangeInProgress && this._isOpen && this._ignoreResizeTo === 0 ) {
8490 this._expectResizeEvent();
8491 this._orientationchangeInProgress = true;
8495 // When the popup is open, attempting to focus on an element that is not a
8496 // child of the popup will redirect focus to the popup
8497 _handleDocumentFocusIn: function( e ) {
8498 var tgt = e.target, $tgt, ui = this._ui;
8500 if ( !this._isOpen ) {
8504 if ( tgt !== ui.container[ 0 ] ) {
8505 $tgt = $( e.target );
8506 if ( 0 === $tgt.parents().filter( ui.container[ 0 ] ).length ) {
8507 $( document.activeElement ).one( "focus", function( e ) {
8510 ui.focusElement.focus();
8512 e.stopImmediatePropagation();
8514 } else if ( ui.focusElement[ 0 ] === ui.container[ 0 ] ) {
8515 ui.focusElement = $tgt;
8519 this._ignoreResizeEvents();
8522 _create: function() {
8524 screen: $( "<div class='ui-screen-hidden ui-popup-screen'></div>" ),
8525 placeholder: $( "<div style='display: none;'><!-- placeholder --></div>" ),
8526 container: $( "<div class='ui-popup-container ui-popup-hidden'></div>" )
8528 thisPage = this.element.closest( ".ui-page" ),
8529 myId = this.element.attr( "id" ),
8532 // We need to adjust the history option to be false if there's no AJAX nav.
8533 // We can't do it in the option declarations because those are run before
8534 // it is determined whether there shall be AJAX nav.
8535 this.options.history = this.options.history && $.mobile.ajaxEnabled && $.mobile.hashListeningEnabled;
8537 if ( thisPage.length === 0 ) {
8538 thisPage = $( "body" );
8541 // define the container for navigation event bindings
8542 // TODO this would be nice at the the mobile widget level
8543 this.options.container = this.options.container || $.mobile.pageContainer;
8546 thisPage.append( ui.screen );
8547 ui.container.insertAfter( ui.screen );
8548 // Leave a placeholder where the element used to be
8549 ui.placeholder.insertAfter( this.element );
8551 ui.screen.attr( "id", myId + "-screen" );
8552 ui.container.attr( "id", myId + "-popup" );
8553 ui.placeholder.html( "<!-- placeholder for " + myId + " -->" );
8555 ui.container.append( this.element );
8556 ui.focusElement = ui.container;
8558 // Add class to popup element
8559 this.element.addClass( "ui-popup" );
8561 // Define instance variables
8566 _fallbackTransition: "",
8567 _currentTransition: false,
8573 _orientationchangeInProgress: false
8576 $.each( this.options, function( key, value ) {
8577 // Cause initial options to be applied by their handler by temporarily setting the option to undefined
8578 // - the handler then sets it to the initial value
8579 self.options[ key ] = undefined;
8580 self._setOption( key, value, true );
8583 ui.screen.bind( "vclick", $.proxy( this, "_eatEventAndClose" ) );
8585 this._on( $.mobile.window, {
8586 orientationchange: $.proxy( this, "_handleWindowOrientationchange" ),
8587 resize: $.proxy( this, "_handleWindowResize" ),
8588 keyup: $.proxy( this, "_handleWindowKeyUp" )
8590 this._on( $.mobile.document, {
8591 focusin: $.proxy( this, "_handleDocumentFocusIn" )
8595 _applyTheme: function( dst, theme, prefix ) {
8596 var classes = ( dst.attr( "class" ) || "").split( " " ),
8597 alreadyAdded = true,
8598 currentTheme = null,
8600 themeStr = String( theme );
8602 while ( classes.length > 0 ) {
8603 currentTheme = classes.pop();
8604 matches = ( new RegExp( "^ui-" + prefix + "-([a-z])$" ) ).exec( currentTheme );
8605 if ( matches && matches.length > 1 ) {
8606 currentTheme = matches[ 1 ];
8609 currentTheme = null;
8613 if ( theme !== currentTheme ) {
8614 dst.removeClass( "ui-" + prefix + "-" + currentTheme );
8615 if ( ! ( theme === null || theme === "none" ) ) {
8616 dst.addClass( "ui-" + prefix + "-" + themeStr );
8621 _setTheme: function( value ) {
8622 this._applyTheme( this.element, value, "body" );
8625 _setOverlayTheme: function( value ) {
8626 this._applyTheme( this._ui.screen, value, "overlay" );
8628 if ( this._isOpen ) {
8629 this._ui.screen.addClass( "in" );
8633 _setShadow: function( value ) {
8634 this.element.toggleClass( "ui-overlay-shadow", value );
8637 _setCorners: function( value ) {
8638 this.element.toggleClass( "ui-corner-all", value );
8641 _applyTransition: function( value ) {
8642 this._ui.container.removeClass( this._fallbackTransition );
8643 if ( value && value !== "none" ) {
8644 this._fallbackTransition = $.mobile._maybeDegradeTransition( value );
8645 if ( this._fallbackTransition === "none" ) {
8646 this._fallbackTransition = "";
8648 this._ui.container.addClass( this._fallbackTransition );
8652 _setTransition: function( value ) {
8653 if ( !this._currentTransition ) {
8654 this._applyTransition( value );
8658 _setTolerance: function( value ) {
8659 var tol = { t: 30, r: 15, b: 30, l: 15 };
8661 if ( value !== undefined ) {
8662 var ar = String( value ).split( "," );
8664 $.each( ar, function( idx, val ) { ar[ idx ] = parseInt( val, 10 ); } );
8666 switch( ar.length ) {
8667 // All values are to be the same
8669 if ( !isNaN( ar[ 0 ] ) ) {
8670 tol.t = tol.r = tol.b = tol.l = ar[ 0 ];
8674 // The first value denotes top/bottom tolerance, and the second value denotes left/right tolerance
8676 if ( !isNaN( ar[ 0 ] ) ) {
8677 tol.t = tol.b = ar[ 0 ];
8679 if ( !isNaN( ar[ 1 ] ) ) {
8680 tol.l = tol.r = ar[ 1 ];
8684 // The array contains values in the order top, right, bottom, left
8686 if ( !isNaN( ar[ 0 ] ) ) {
8689 if ( !isNaN( ar[ 1 ] ) ) {
8692 if ( !isNaN( ar[ 2 ] ) ) {
8695 if ( !isNaN( ar[ 3 ] ) ) {
8705 this._tolerance = tol;
8708 _setOption: function( key, value ) {
8709 var exclusions, setter = "_set" + key.charAt( 0 ).toUpperCase() + key.slice( 1 );
8711 if ( this[ setter ] !== undefined ) {
8712 this[ setter ]( value );
8715 // TODO REMOVE FOR 1.2.1 by moving them out to a default options object
8718 "closeLinkSelector",
8726 $.mobile.widget.prototype._setOption.apply( this, arguments );
8727 if ( $.inArray( key, exclusions ) === -1 ) {
8728 // Record the option change in the options and in the DOM data-* attributes
8729 this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value );
8733 // Try and center the overlay over the given coordinates
8734 _placementCoords: function( desired ) {
8735 // rectangle within which the popup must fit
8737 winCoords = windowCoords(),
8739 x: this._tolerance.l,
8740 y: winCoords.y + this._tolerance.t,
8741 cx: winCoords.cx - this._tolerance.l - this._tolerance.r,
8742 cy: winCoords.cy - this._tolerance.t - this._tolerance.b
8746 // Clamp the width of the menu before grabbing its size
8747 this._ui.container.css( "max-width", rc.cx );
8749 cx: this._ui.container.outerWidth( true ),
8750 cy: this._ui.container.outerHeight( true )
8753 // Center the menu over the desired coordinates, while not going outside
8754 // the window tolerances. This will center wrt. the window if the popup is too large.
8756 x: fitSegmentInsideSegment( rc.cx, menuSize.cx, rc.x, desired.x ),
8757 y: fitSegmentInsideSegment( rc.cy, menuSize.cy, rc.y, desired.y )
8760 // Make sure the top of the menu is visible
8761 ret.y = Math.max( 0, ret.y );
8763 // If the height of the menu is smaller than the height of the document
8764 // align the bottom with the bottom of the document
8766 // fix for $.mobile.document.height() bug in core 1.7.2.
8767 var docEl = document.documentElement, docBody = document.body,
8768 docHeight = Math.max( docEl.clientHeight, docBody.scrollHeight, docBody.offsetHeight, docEl.scrollHeight, docEl.offsetHeight );
8770 ret.y -= Math.min( ret.y, Math.max( 0, ret.y + menuSize.cy - docHeight ) );
8772 return { left: ret.x, top: ret.y };
8775 _createPrereqs: function( screenPrereq, containerPrereq, whenDone ) {
8776 var self = this, prereqs;
8778 // It is important to maintain both the local variable prereqs and self._prereqs. The local variable remains in
8779 // the closure of the functions which call the callbacks passed in. The comparison between the local variable and
8780 // self._prereqs is necessary, because once a function has been passed to .animationComplete() it will be called
8781 // next time an animation completes, even if that's not the animation whose end the function was supposed to catch
8782 // (for example, if an abort happens during the opening animation, the .animationComplete handler is not called for
8783 // that animation anymore, but the handler remains attached, so it is called the next time the popup is opened
8784 // - making it stale. Comparing the local variable prereqs to the widget-level variable self._prereqs ensures that
8785 // callbacks triggered by a stale .animationComplete will be ignored.
8788 screen: $.Deferred(),
8789 container: $.Deferred()
8792 prereqs.screen.then( function() {
8793 if ( prereqs === self._prereqs ) {
8798 prereqs.container.then( function() {
8799 if ( prereqs === self._prereqs ) {
8804 $.when( prereqs.screen, prereqs.container ).done( function() {
8805 if ( prereqs === self._prereqs ) {
8806 self._prereqs = null;
8811 self._prereqs = prereqs;
8814 _animate: function( args ) {
8815 // NOTE before removing the default animation of the screen
8816 // this had an animate callback that would resolve the deferred
8817 // now the deferred is resolved immediately
8818 // TODO remove the dependency on the screen deferred
8820 .removeClass( args.classToRemove )
8821 .addClass( args.screenClassToAdd );
8823 args.prereqs.screen.resolve();
8825 if ( args.transition && args.transition !== "none" ) {
8826 if ( args.applyTransition ) {
8827 this._applyTransition( args.transition );
8829 if ( this._fallbackTransition ) {
8831 .animationComplete( $.proxy( args.prereqs.container, "resolve" ) )
8832 .addClass( args.containerClassToAdd )
8833 .removeClass( args.classToRemove );
8837 this._ui.container.removeClass( args.classToRemove );
8838 args.prereqs.container.resolve();
8841 // The desired coordinates passed in will be returned untouched if no reference element can be identified via
8842 // desiredPosition.positionTo. Nevertheless, this function ensures that its return value always contains valid
8843 // x and y coordinates by specifying the center middle of the window if the coordinates are absent.
8844 // options: { x: coordinate, y: coordinate, positionTo: string: "origin", "window", or jQuery selector
8845 _desiredCoords: function( o ) {
8846 var dst = null, offset, winCoords = windowCoords(), x = o.x, y = o.y, pTo = o.positionTo;
8848 // Establish which element will serve as the reference
8849 if ( pTo && pTo !== "origin" ) {
8850 if ( pTo === "window" ) {
8851 x = winCoords.cx / 2 + winCoords.x;
8852 y = winCoords.cy / 2 + winCoords.y;
8860 dst.filter( ":visible" );
8861 if ( dst.length === 0 ) {
8868 // If an element was found, center over it
8870 offset = dst.offset();
8871 x = offset.left + dst.outerWidth() / 2;
8872 y = offset.top + dst.outerHeight() / 2;
8875 // Make sure x and y are valid numbers - center over the window
8876 if ( $.type( x ) !== "number" || isNaN( x ) ) {
8877 x = winCoords.cx / 2 + winCoords.x;
8879 if ( $.type( y ) !== "number" || isNaN( y ) ) {
8880 y = winCoords.cy / 2 + winCoords.y;
8883 return { x: x, y: y };
8886 _reposition: function( o ) {
8887 // We only care about position-related parameters for repositioning
8888 o = { x: o.x, y: o.y, positionTo: o.positionTo };
8889 this._trigger( "beforeposition", o );
8890 this._ui.container.offset( this._placementCoords( this._desiredCoords( o ) ) );
8893 reposition: function( o ) {
8894 if ( this._isOpen ) {
8895 this._reposition( o );
8899 _openPrereqsComplete: function() {
8900 this._ui.container.addClass( "ui-popup-active" );
8901 this._isOpen = true;
8902 this._resizeScreen();
8903 this._ui.container.attr( "tabindex", "0" ).focus();
8904 this._ignoreResizeEvents();
8905 this._trigger( "afteropen" );
8908 _open: function( options ) {
8909 var o = $.extend( {}, this.options, options ),
8910 // TODO move blacklist to private method
8911 androidBlacklist = ( function() {
8913 ua = navigator.userAgent,
8914 // Rendering engine is Webkit, and capture major version
8915 wkmatch = ua.match( /AppleWebKit\/([0-9\.]+)/ ),
8916 wkversion = !!wkmatch && wkmatch[ 1 ],
8917 androidmatch = ua.match( /Android (\d+(?:\.\d+))/ ),
8918 andversion = !!androidmatch && androidmatch[ 1 ],
8919 chromematch = ua.indexOf( "Chrome" ) > -1;
8921 // Platform is Android, WebKit version is greater than 534.13 ( Android 3.2.1 ) and not Chrome.
8922 if( androidmatch !== null && andversion === "4.0" && wkversion && wkversion > 534.13 && !chromematch ) {
8928 // Count down to triggering "popupafteropen" - we have two prerequisites:
8929 // 1. The popup window animation completes (container())
8930 // 2. The screen opacity animation completes (screen())
8931 this._createPrereqs(
8934 $.proxy( this, "_openPrereqsComplete" ) );
8936 this._currentTransition = o.transition;
8937 this._applyTransition( o.transition );
8939 if ( !this.options.theme ) {
8940 this._setTheme( this._page.jqmData( "theme" ) || $.mobile.getInheritedTheme( this._page, "c" ) );
8943 this._ui.screen.removeClass( "ui-screen-hidden" );
8944 this._ui.container.removeClass( "ui-popup-hidden" );
8946 // Give applications a chance to modify the contents of the container before it appears
8947 this._reposition( o );
8949 if ( this.options.overlayTheme && androidBlacklist ) {
8951 The native browser on Android 4.0.X ("Ice Cream Sandwich") suffers from an issue where the popup overlay appears to be z-indexed
8952 above the popup itself when certain other styles exist on the same page -- namely, any element set to `position: fixed` and certain
8953 types of input. These issues are reminiscent of previously uncovered bugs in older versions of Android's native browser:
8954 https://github.com/scottjehl/Device-Bugs/issues/3
8956 This fix closes the following bugs ( I use "closes" with reluctance, and stress that this issue should be revisited as soon as possible ):
8958 https://github.com/jquery/jquery-mobile/issues/4816
8959 https://github.com/jquery/jquery-mobile/issues/4844
8960 https://github.com/jquery/jquery-mobile/issues/4874
8963 // TODO sort out why this._page isn't working
8964 this.element.closest( ".ui-page" ).addClass( "ui-popup-open" );
8967 additionalCondition: true,
8968 transition: o.transition,
8970 screenClassToAdd: "in",
8971 containerClassToAdd: "in",
8972 applyTransition: false,
8973 prereqs: this._prereqs
8977 _closePrereqScreen: function() {
8979 .removeClass( "out" )
8980 .addClass( "ui-screen-hidden" );
8983 _closePrereqContainer: function() {
8985 .removeClass( "reverse out" )
8986 .addClass( "ui-popup-hidden" )
8987 .removeAttr( "style" );
8990 _closePrereqsDone: function() {
8991 var opts = this.options;
8993 this._ui.container.removeAttr( "tabindex" );
8995 // remove the global mutex for popups
8996 $.mobile.popup.active = undefined;
8998 // alert users that the popup is closed
8999 this._trigger( "afterclose" );
9002 _close: function( immediate ) {
9003 this._ui.container.removeClass( "ui-popup-active" );
9004 this._page.removeClass( "ui-popup-open" );
9006 this._isOpen = false;
9008 // Count down to triggering "popupafterclose" - we have two prerequisites:
9009 // 1. The popup window reverse animation completes (container())
9010 // 2. The screen opacity animation completes (screen())
9011 this._createPrereqs(
9012 $.proxy( this, "_closePrereqScreen" ),
9013 $.proxy( this, "_closePrereqContainer" ),
9014 $.proxy( this, "_closePrereqsDone" ) );
9017 additionalCondition: this._ui.screen.hasClass( "in" ),
9018 transition: ( immediate ? "none" : ( this._currentTransition ) ),
9019 classToRemove: "in",
9020 screenClassToAdd: "out",
9021 containerClassToAdd: "reverse out",
9022 applyTransition: true,
9023 prereqs: this._prereqs
9027 _unenhance: function() {
9028 // Put the element back to where the placeholder was and remove the "ui-popup" class
9029 this._setTheme( "none" );
9031 // Cannot directly insertAfter() - we need to detach() first, because
9032 // insertAfter() will do nothing if the payload div was not attached
9033 // to the DOM at the time the widget was created, and so the payload
9034 // will remain inside the container even after we call insertAfter().
9035 // If that happens and we remove the container a few lines below, we
9036 // will cause an infinite recursion - #5244
9038 .insertAfter( this._ui.placeholder )
9039 .removeClass( "ui-popup ui-overlay-shadow ui-corner-all" );
9040 this._ui.screen.remove();
9041 this._ui.container.remove();
9042 this._ui.placeholder.remove();
9045 _destroy: function() {
9046 if ( $.mobile.popup.active === this ) {
9047 this.element.one( "popupafterclose", $.proxy( this, "_unenhance" ) );
9054 _closePopup: function( e, data ) {
9055 var parsedDst, toUrl, o = this.options, immediate = false;
9057 // restore location on screen
9058 window.scrollTo( 0, this._scrollTop );
9060 if ( e && e.type === "pagebeforechange" && data ) {
9061 // Determine whether we need to rapid-close the popup, or whether we can
9062 // take the time to run the closing transition
9063 if ( typeof data.toPage === "string" ) {
9064 parsedDst = data.toPage;
9066 parsedDst = data.toPage.jqmData( "url" );
9068 parsedDst = $.mobile.path.parseUrl( parsedDst );
9069 toUrl = parsedDst.pathname + parsedDst.search + parsedDst.hash;
9071 if ( this._myUrl !== $.mobile.path.makeUrlAbsolute( toUrl ) ) {
9072 // Going to a different page - close immediately
9079 // remove nav bindings
9080 o.container.unbind( o.closeEvents );
9081 // unbind click handlers added when history is disabled
9082 this.element.undelegate( o.closeLinkSelector, o.closeLinkEvents );
9084 this._close( immediate );
9087 // any navigation event after a popup is opened should close the popup
9088 // NOTE the pagebeforechange is bound to catch navigation events that don't
9089 // alter the url (eg, dialogs from popups)
9090 _bindContainerClose: function() {
9091 this.options.container
9092 .one( this.options.closeEvents, $.proxy( this, "_closePopup" ) );
9095 // TODO no clear deliniation of what should be here and
9096 // what should be in _open. Seems to be "visual" vs "history" for now
9097 open: function( options ) {
9098 var self = this, opts = this.options, url, hashkey, activePage, currentIsDialog, hasHash, urlHistory;
9100 // make sure open is idempotent
9101 if( $.mobile.popup.active ) {
9105 // set the global popup mutex
9106 $.mobile.popup.active = this;
9107 this._scrollTop = $.mobile.window.scrollTop();
9109 // if history alteration is disabled close on navigate events
9110 // and leave the url as is
9111 if( !( opts.history ) ) {
9112 self._open( options );
9113 self._bindContainerClose();
9115 // When histoy is disabled we have to grab the data-rel
9116 // back link clicks so we can close the popup instead of
9117 // relying on history to do it for us
9119 .delegate( opts.closeLinkSelector, opts.closeLinkEvents, function( e ) {
9127 // cache some values for min/readability
9128 urlHistory = $.mobile.urlHistory;
9129 hashkey = $.mobile.dialogHashKey;
9130 activePage = $.mobile.activePage;
9131 currentIsDialog = activePage.is( ".ui-dialog" );
9132 this._myUrl = url = urlHistory.getActive().url;
9133 hasHash = ( url.indexOf( hashkey ) > -1 ) && !currentIsDialog && ( urlHistory.activeIndex > 0 );
9136 self._open( options );
9137 self._bindContainerClose();
9141 // if the current url has no dialog hash key proceed as normal
9142 // otherwise, if the page is a dialog simply tack on the hash key
9143 if ( url.indexOf( hashkey ) === -1 && !currentIsDialog ){
9144 url = url + (url.indexOf( "#" ) > -1 ? hashkey : "#" + hashkey);
9146 url = $.mobile.path.parseLocation().hash + hashkey;
9149 // Tack on an extra hashkey if this is the first page and we've just reconstructed the initial hash
9150 if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) {
9154 // swallow the the initial navigation event, and bind for the next
9155 $(window).one( "beforenavigate", function( e ) {
9157 self._open( options );
9158 self._bindContainerClose();
9161 this.urlAltered = true;
9162 $.mobile.navigate( url, {role: "dialog"} );
9166 // make sure close is idempotent
9167 if( $.mobile.popup.active !== this ) {
9171 this._scrollTop = $.mobile.window.scrollTop();
9173 if( this.options.history && this.urlAltered ) {
9175 this.urlAltered = false;
9177 // simulate the nav bindings having fired
9184 // TODO this can be moved inside the widget
9185 $.mobile.popup.handleLink = function( $link ) {
9186 var closestPage = $link.closest( ":jqmData(role='page')" ),
9187 scope = ( ( closestPage.length === 0 ) ? $( "body" ) : closestPage ),
9188 // NOTE make sure to get only the hash, ie7 (wp7) return the absolute href
9189 // in this case ruining the element selection
9190 popup = $( $.mobile.path.parseUrl($link.attr( "href" )).hash, scope[0] ),
9193 if ( popup.data( "mobile-popup" ) ) {
9194 offset = $link.offset();
9195 popup.popup( "open", {
9196 x: offset.left + $link.outerWidth() / 2,
9197 y: offset.top + $link.outerHeight() / 2,
9198 transition: $link.jqmData( "transition" ),
9199 positionTo: $link.jqmData( "position-to" )
9203 //remove after delay
9204 setTimeout( function() {
9205 // Check if we are in a listview
9206 var $parent = $link.parent().parent();
9207 if ($parent.hasClass("ui-li")) {
9208 $link = $parent.parent();
9210 $link.removeClass( $.mobile.activeBtnClass );
9214 // TODO move inside _create
9215 $.mobile.document.bind( "pagebeforechange", function( e, data ) {
9216 if ( data.options.role === "popup" ) {
9217 $.mobile.popup.handleLink( data.options.link );
9222 $.mobile.document.bind( "pagecreate create", function( e ) {
9223 $.mobile.popup.prototype.enhanceWithin( e.target, true );
9229 * custom "selectmenu" plugin
9232 (function( $, undefined ) {
9233 var extendSelect = function( widget ) {
9235 var select = widget.select,
9236 origDestroy = widget._destroy,
9237 selectID = widget.selectID,
9238 prefix = ( selectID ? selectID : ( ( $.mobile.ns || "" ) + "uuid-" + widget.uuid ) ),
9239 popupID = prefix + "-listbox",
9240 dialogID = prefix + "-dialog",
9241 label = widget.label,
9242 thisPage = widget.select.closest( ".ui-page" ),
9243 selectOptions = widget._selectOptions(),
9244 isMultiple = widget.isMultiple = widget.select[ 0 ].multiple,
9245 buttonId = selectID + "-button",
9246 menuId = selectID + "-menu",
9247 menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' id='" + dialogID + "' data-" +$.mobile.ns + "theme='"+ widget.options.theme +"' data-" +$.mobile.ns + "overlay-theme='"+ widget.options.overlayTheme +"'>" +
9248 "<div data-" + $.mobile.ns + "role='header'>" +
9249 "<div class='ui-title'>" + label.getEncodedText() + "</div>"+
9251 "<div data-" + $.mobile.ns + "role='content'></div>"+
9254 listbox = $( "<div id='" + popupID + "' class='ui-selectmenu'>" ).insertAfter( widget.select ).popup( { theme: widget.options.overlayTheme } ),
9257 "class": "ui-selectmenu-list",
9260 "aria-labelledby": buttonId
9261 }).attr( "data-" + $.mobile.ns + "theme", widget.options.theme )
9262 .attr( "data-" + $.mobile.ns + "divider-theme", widget.options.dividerTheme )
9263 .appendTo( listbox ),
9266 header = $( "<div>", {
9267 "class": "ui-header ui-bar-" + widget.options.theme
9268 }).prependTo( listbox ),
9270 headerTitle = $( "<h1>", {
9272 }).appendTo( header ),
9278 if ( widget.isMultiple ) {
9279 headerClose = $( "<a>", {
9280 "text": widget.options.closeText,
9282 "class": "ui-btn-left"
9283 }).attr( "data-" + $.mobile.ns + "iconpos", "notext" ).attr( "data-" + $.mobile.ns + "icon", "delete" ).appendTo( header ).buttonMarkup();
9287 select: widget.select,
9296 selectOptions: selectOptions,
9297 isMultiple: isMultiple,
9298 theme: widget.options.theme,
9302 headerTitle: headerTitle,
9303 headerClose: headerClose,
9304 menuPageContent: menuPageContent,
9305 menuPageClose: menuPageClose,
9311 // Create list from select, update state
9314 if ( self._origTabIndex === undefined ) {
9315 // Map undefined to false, because self._origTabIndex === undefined
9316 // indicates that we have not yet checked whether the select has
9317 // originally had a tabindex attribute, whereas false indicates that
9318 // we have checked the select for such an attribute, and have found
9320 self._origTabIndex = ( self.select[ 0 ].getAttribute( "tabindex" ) === null ) ? false : self.select.attr( "tabindex" );
9322 self.select.attr( "tabindex", "-1" ).focus(function() {
9324 self.button.focus();
9328 self.button.bind( "vclick keydown" , function( event ) {
9329 if ( self.options.disabled || self.isOpen ) {
9333 if (event.type === "vclick" ||
9334 event.keyCode && (event.keyCode === $.mobile.keyCode.ENTER ||
9335 event.keyCode === $.mobile.keyCode.SPACE)) {
9337 self._decideFormat();
9338 if ( self.menuType === "overlay" ) {
9339 self.button.attr( "href", "#" + self.popupID ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "popup" );
9341 self.button.attr( "href", "#" + self.dialogID ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "dialog" );
9344 // Do not prevent default, so the navigation may have a chance to actually open the chosen format
9348 // Events for list items
9349 self.list.attr( "role", "listbox" )
9350 .bind( "focusin", function( e ) {
9352 .attr( "tabindex", "0" )
9353 .trigger( "vmouseover" );
9356 .bind( "focusout", function( e ) {
9358 .attr( "tabindex", "-1" )
9359 .trigger( "vmouseout" );
9361 .delegate( "li:not(.ui-disabled, .ui-li-divider)", "click", function( event ) {
9363 // index of option tag to be selected
9364 var oldIndex = self.select[ 0 ].selectedIndex,
9365 newIndex = self.list.find( "li:not(.ui-li-divider)" ).index( this ),
9366 option = self._selectOptions().eq( newIndex )[ 0 ];
9368 // toggle selected status on the tag for multi selects
9369 option.selected = self.isMultiple ? !option.selected : true;
9371 // toggle checkbox class for multiple selects
9372 if ( self.isMultiple ) {
9373 $( this ).find( ".ui-icon" )
9374 .toggleClass( "ui-icon-checkbox-on", option.selected )
9375 .toggleClass( "ui-icon-checkbox-off", !option.selected );
9378 // trigger change if value changed
9379 if ( self.isMultiple || oldIndex !== newIndex ) {
9380 self.select.trigger( "change" );
9383 // hide custom select for single selects only - otherwise focus clicked item
9384 // We need to grab the clicked item the hard way, because the list may have been rebuilt
9385 if ( self.isMultiple ) {
9386 self.list.find( "li:not(.ui-li-divider)" ).eq( newIndex )
9387 .addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
9393 event.preventDefault();
9395 .keydown(function( event ) { //keyboard events for menu items
9396 var target = $( event.target ),
9397 li = target.closest( "li" ),
9400 // switch logic based on which key was pressed
9401 switch ( event.keyCode ) {
9402 // up or left arrow keys
9404 prev = li.prev().not( ".ui-selectmenu-placeholder" );
9406 if ( prev.is( ".ui-li-divider" ) ) {
9410 // if there's a previous option, focus it
9411 if ( prev.length ) {
9414 .attr( "tabindex", "-1" );
9416 prev.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
9420 // down or right arrow keys
9424 if ( next.is( ".ui-li-divider" ) ) {
9428 // if there's a next option, focus it
9429 if ( next.length ) {
9432 .attr( "tabindex", "-1" );
9434 next.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
9438 // If enter or space is pressed, trigger click
9441 target.trigger( "click" );
9447 // button refocus ensures proper height calculation
9448 // by removing the inline style and ensuring page inclusion
9449 self.menuPage.bind( "pagehide", function() {
9450 // TODO centralize page removal binding / handling in the page plugin.
9451 // Suggestion from @jblas to do refcounting
9453 // TODO extremely confusing dependency on the open method where the pagehide.remove
9454 // bindings are stripped to prevent the parent page from disappearing. The way
9455 // we're keeping pages in the DOM right now sucks
9457 // rebind the page remove that was unbound in the open function
9458 // to allow for the parent page removal from actions other than the use
9459 // of a dialog sized custom select
9461 // doing this here provides for the back button on the custom select dialog
9462 $.mobile._bindPageRemove.call( self.thisPage );
9465 // Events on the popup
9466 self.listbox.bind( "popupafterclose", function( event ) {
9470 // Close button on small overlays
9471 if ( self.isMultiple ) {
9472 self.headerClose.click(function() {
9473 if ( self.menuType === "overlay" ) {
9480 // track this dependency so that when the parent page
9481 // is removed on pagehide it will also remove the menupage
9482 self.thisPage.addDependents( this.menuPage );
9485 _isRebuildRequired: function() {
9486 var list = this.list.find( "li" ),
9487 options = this._selectOptions();
9489 // TODO exceedingly naive method to determine difference
9490 // ignores value changes etc in favor of a forcedRebuild
9491 // from the user in the refresh method
9492 return options.text() !== list.text();
9495 selected: function() {
9496 return this._selectOptions().filter( ":selected:not( :jqmData(placeholder='true') )" );
9499 refresh: function( forceRebuild , foo ) {
9501 select = this.element,
9502 isMultiple = this.isMultiple,
9505 if ( forceRebuild || this._isRebuildRequired() ) {
9509 indicies = this.selectedIndices();
9511 self.setButtonText();
9512 self.setButtonCount();
9514 self.list.find( "li:not(.ui-li-divider)" )
9515 .removeClass( $.mobile.activeBtnClass )
9516 .attr( "aria-selected", false )
9517 .each(function( i ) {
9519 if ( $.inArray( i, indicies ) > -1 ) {
9520 var item = $( this );
9522 // Aria selected attr
9523 item.attr( "aria-selected", true );
9525 // Multiple selects: add the "on" checkbox state to the icon
9526 if ( self.isMultiple ) {
9527 item.find( ".ui-icon" ).removeClass( "ui-icon-checkbox-off" ).addClass( "ui-icon-checkbox-on" );
9529 if ( item.is( ".ui-selectmenu-placeholder" ) ) {
9530 item.next().addClass( $.mobile.activeBtnClass );
9532 item.addClass( $.mobile.activeBtnClass );
9540 if ( this.options.disabled || !this.isOpen ) {
9546 if ( self.menuType === "page" ) {
9547 self.menuPage.dialog( "close" );
9548 self.list.appendTo( self.listbox );
9550 self.listbox.popup( "close" );
9553 self._focusButton();
9554 // allow the dialog to be closed again
9555 self.isOpen = false;
9559 this.button.click();
9562 _decideFormat: function() {
9564 $window = $.mobile.window,
9565 selfListParent = self.list.parent(),
9566 menuHeight = selfListParent.outerHeight(),
9567 menuWidth = selfListParent.outerWidth(),
9568 activePage = $( "." + $.mobile.activePageClass ),
9569 scrollTop = $window.scrollTop(),
9570 btnOffset = self.button.offset().top,
9571 screenHeight = $window.height(),
9572 screenWidth = $window.width();
9574 function focusMenuItem() {
9575 var selector = self.list.find( "." + $.mobile.activeBtnClass + " a" );
9576 if ( selector.length === 0 ) {
9577 selector = self.list.find( "li.ui-btn:not( :jqmData(placeholder='true') ) a" );
9579 selector.first().focus().closest( "li" ).addClass( "ui-btn-down-" + widget.options.theme );
9582 if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) {
9584 self.menuPage.appendTo( $.mobile.pageContainer ).page();
9585 self.menuPageContent = menuPage.find( ".ui-content" );
9586 self.menuPageClose = menuPage.find( ".ui-header a" );
9588 // prevent the parent page from being removed from the DOM,
9589 // otherwise the results of selecting a list item in the dialog
9590 // fall into a black hole
9591 self.thisPage.unbind( "pagehide.remove" );
9593 //for WebOS/Opera Mini (set lastscroll using button offset)
9594 if ( scrollTop === 0 && btnOffset > screenHeight ) {
9595 self.thisPage.one( "pagehide", function() {
9596 $( this ).jqmData( "lastScroll", btnOffset );
9601 .one( "pageshow", function() {
9604 .one( "pagehide", function() {
9608 self.menuType = "page";
9609 self.menuPageContent.append( self.list );
9610 self.menuPage.find("div .ui-title").text(self.label.text());
9612 self.menuType = "overlay";
9614 self.listbox.one( "popupafteropen", focusMenuItem );
9618 _buildList: function() {
9621 placeholder = this.placeholder,
9622 needPlaceholder = true,
9625 dataIcon = self.isMultiple ? "checkbox-off" : "false";
9627 self.list.empty().filter( ".ui-listview" ).listview( "destroy" );
9629 var $options = self.select.find( "option" ),
9630 numOptions = $options.length,
9631 select = this.select[ 0 ],
9632 dataPrefix = 'data-' + $.mobile.ns,
9633 dataIndexAttr = dataPrefix + 'option-index',
9634 dataIconAttr = dataPrefix + 'icon',
9635 dataRoleAttr = dataPrefix + 'role',
9636 dataPlaceholderAttr = dataPrefix + 'placeholder',
9637 fragment = document.createDocumentFragment(),
9638 isPlaceholderItem = false,
9641 for (var i = 0; i < numOptions;i++, isPlaceholderItem = false) {
9642 var option = $options[i],
9643 $option = $( option ),
9644 parent = option.parentNode,
9645 text = $option.text(),
9646 anchor = document.createElement( 'a' ),
9649 anchor.setAttribute( 'href', '#' );
9650 anchor.appendChild( document.createTextNode( text ) );
9652 // Are we inside an optgroup?
9653 if ( parent !== select && parent.nodeName.toLowerCase() === "optgroup" ) {
9654 var optLabel = parent.getAttribute( 'label' );
9655 if ( optLabel !== optGroup ) {
9656 var divider = document.createElement( 'li' );
9657 divider.setAttribute( dataRoleAttr, 'list-divider' );
9658 divider.setAttribute( 'role', 'option' );
9659 divider.setAttribute( 'tabindex', '-1' );
9660 divider.appendChild( document.createTextNode( optLabel ) );
9661 fragment.appendChild( divider );
9662 optGroup = optLabel;
9666 if ( needPlaceholder && ( !option.getAttribute( "value" ) || text.length === 0 || $option.jqmData( "placeholder" ) ) ) {
9667 needPlaceholder = false;
9668 isPlaceholderItem = true;
9670 // If we have identified a placeholder, record the fact that it was
9671 // us who have added the placeholder to the option and mark it
9672 // retroactively in the select as well
9673 if ( null === option.getAttribute( dataPlaceholderAttr ) ) {
9674 this._removePlaceholderAttr = true;
9676 option.setAttribute( dataPlaceholderAttr, true );
9677 if ( o.hidePlaceholderMenuItems ) {
9678 classes.push( "ui-selectmenu-placeholder" );
9680 if ( placeholder !== text ) {
9681 placeholder = self.placeholder = text;
9685 var item = document.createElement('li');
9686 if ( option.disabled ) {
9687 classes.push( "ui-disabled" );
9688 item.setAttribute('aria-disabled',true);
9690 item.setAttribute( dataIndexAttr,i );
9691 item.setAttribute( dataIconAttr, dataIcon );
9692 if ( isPlaceholderItem ) {
9693 item.setAttribute( dataPlaceholderAttr, true );
9695 item.className = classes.join( " " );
9696 item.setAttribute( 'role', 'option' );
9697 anchor.setAttribute( 'tabindex', '-1' );
9698 item.appendChild( anchor );
9699 fragment.appendChild( item );
9702 self.list[0].appendChild( fragment );
9704 // Hide header if it's not a multiselect and there's no placeholder
9705 if ( !this.isMultiple && !placeholder.length ) {
9708 this.headerTitle.text( this.placeholder );
9711 // Now populated, create listview
9712 self.list.listview();
9715 _button: function() {
9719 // TODO value is undefined at creation
9720 "id": this.buttonId,
9721 "aria-haspopup": "true",
9723 // TODO value is undefined at creation
9724 "aria-owns": this.menuId
9728 _destroy: function() {
9731 // Restore the tabindex attribute to its original value
9732 if ( this._origTabIndex !== undefined ) {
9733 if ( this._origTabIndex !== false ) {
9734 this.select.attr( "tabindex", this._origTabIndex );
9736 this.select.removeAttr( "tabindex" );
9740 // Remove the placeholder attribute if we were the ones to add it
9741 if ( this._removePlaceholderAttr ) {
9742 this._selectOptions().removeAttr( "data-" + $.mobile.ns + "placeholder" );
9746 this.listbox.remove();
9749 origDestroy.apply( this, arguments );
9754 // issue #3894 - core doesn't trigger events on disabled delegates
9755 $.mobile.document.bind( "selectmenubeforecreate", function( event ) {
9756 var selectmenuWidget = $( event.target ).data( "mobile-selectmenu" );
9758 if ( !selectmenuWidget.options.nativeMenu &&
9759 selectmenuWidget.element.parents( ":jqmData(role='popup')" ).length === 0 ) {
9760 extendSelect( selectmenuWidget );
9765 (function( $, undefined ) {
9767 $.widget( "mobile.controlgroup", $.mobile.widget, $.extend( {
9771 excludeInvisible: true,
9774 initSelector: ":jqmData(role='controlgroup')"
9777 _create: function() {
9778 var $el = this.element,
9780 inner: $( "<div class='ui-controlgroup-controls'></div>" ),
9781 legend: $( "<div role='heading' class='ui-controlgroup-label'></div>" )
9783 grouplegend = $el.children( "legend" ),
9787 $el.wrapInner( ui.inner );
9788 if ( grouplegend.length ) {
9789 ui.legend.append( grouplegend ).insertBefore( $el.children( 0 ) );
9791 $el.addClass( "ui-corner-all ui-controlgroup" );
9794 _initialRefresh: true
9797 $.each( this.options, function( key, value ) {
9798 // Cause initial options to be applied by their handler by temporarily setting the option to undefined
9799 // - the handler then sets it to the initial value
9800 self.options[ key ] = undefined;
9801 self._setOption( key, value, true );
9809 _setOption: function( key, value ) {
9810 var setter = "_set" + key.charAt( 0 ).toUpperCase() + key.slice( 1 );
9812 if ( this[ setter ] !== undefined ) {
9813 this[ setter ]( value );
9816 this._super( key, value );
9817 this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value );
9820 _setType: function( value ) {
9822 .removeClass( "ui-controlgroup-horizontal ui-controlgroup-vertical" )
9823 .addClass( "ui-controlgroup-" + value );
9827 _setCorners: function( value ) {
9828 this.element.toggleClass( "ui-corner-all", value );
9831 _setShadow: function( value ) {
9832 this.element.toggleClass( "ui-shadow", value );
9835 _setMini: function( value ) {
9836 this.element.toggleClass( "ui-mini", value );
9839 container: function() {
9840 return this.element.children( ".ui-controlgroup-controls" );
9843 refresh: function() {
9844 var els = this.element.find( ".ui-btn" ).not( ".ui-slider-handle" ),
9845 create = this._initialRefresh;
9846 if ( $.mobile.checkboxradio ) {
9847 this.element.find( ":mobile-checkboxradio" ).checkboxradio( "refresh" );
9849 this._addFirstLastClasses( els, this.options.excludeInvisible ? this._getVisibles( els, create ) : els, create );
9850 this._initialRefresh = false;
9852 }, $.mobile.behaviors.addFirstLastClasses ) );
9854 // TODO: Implement a mechanism to allow widgets to become enhanced in the
9855 // correct order when their correct enhancement depends on other widgets in
9856 // the page being correctly enhanced already.
9858 // For now, we wait until dom-ready to attach the controlgroup's enhancement
9859 // hook, because by that time, all the other widgets' enhancement hooks should
9860 // already be in place, ensuring that all widgets that need to be grouped will
9861 // already have been enhanced by the time the controlgroup is created.
9863 $.mobile.document.bind( "pagecreate create", function( e ) {
9864 $.mobile.controlgroup.prototype.enhanceWithin( e.target, true );
9869 (function( $, undefined ) {
9871 $( document ).bind( "pagecreate create", function( e ) {
9873 //links within content areas, tests included with page
9877 .not( ".ui-btn, .ui-link-inherit, :jqmData(role='none'), :jqmData(role='nojs')" )
9878 .addClass( "ui-link" );
9885 (function( $, undefined ) {
9888 $.widget( "mobile.fixedtoolbar", $.mobile.widget, {
9890 visibleOnPageShow: true,
9891 disablePageZoom: true,
9892 transition: "slide", //can be none, fade, slide (slide maps to slideup or slidedown)
9895 tapToggleBlacklist: "a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed, .ui-popup, .ui-panel, .ui-panel-dismiss-open",
9896 hideDuringFocus: "input, textarea, select",
9897 updatePagePadding: true,
9898 trackPersistentToolbars: true,
9900 // Browser detection! Weeee, here we go...
9901 // Unfortunately, position:fixed is costly, not to mention probably impossible, to feature-detect accurately.
9902 // Some tests exist, but they currently return false results in critical devices and browsers, which could lead to a broken experience.
9903 // Testing fixed positioning is also pretty obtrusive to page load, requiring injected elements and scrolling the window
9904 // The following function serves to rule out some popular browsers with known fixed-positioning issues
9905 // This is a plugin option like any other, so feel free to improve or overwrite it
9906 supportBlacklist: function() {
9907 return !$.support.fixedPosition;
9909 initSelector: ":jqmData(position='fixed')"
9912 _create: function() {
9917 tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer",
9918 $page = $el.closest( ".ui-page" );
9920 // Feature detecting support for
9921 if ( o.supportBlacklist() ) {
9926 $el.addClass( "ui-"+ tbtype +"-fixed" );
9928 // "fullscreen" overlay positioning
9929 if ( o.fullscreen ) {
9930 $el.addClass( "ui-"+ tbtype +"-fullscreen" );
9931 $page.addClass( "ui-page-" + tbtype + "-fullscreen" );
9933 // If not fullscreen, add class to page to set top or bottom padding
9935 $page.addClass( "ui-page-" + tbtype + "-fixed" );
9942 self._addTransitionClass();
9943 self._bindPageEvents();
9944 self._bindToggleHandlers();
9947 _addTransitionClass: function() {
9948 var tclass = this.options.transition;
9950 if ( tclass && tclass !== "none" ) {
9951 // use appropriate slide for header or footer
9952 if ( tclass === "slide" ) {
9953 tclass = this.element.is( ".ui-header" ) ? "slidedown" : "slideup";
9956 this.element.addClass( tclass );
9960 _bindPageEvents: function() {
9961 this._thisPage = this.element.closest( ".ui-page" );
9962 //page event bindings
9963 // Fixed toolbars require page zoom to be disabled, otherwise usability issues crop up
9964 // This method is meant to disable zoom while a fixed-positioned toolbar page is visible
9965 this._on( this._thisPage, {
9966 "pagebeforeshow": "_handlePageBeforeShow",
9967 "webkitAnimationStart":"_handleAnimationStart",
9968 "animationstart":"_handleAnimationStart",
9969 "updatelayout": "_handleAnimationStart",
9970 "pageshow": "_handlePageShow",
9971 "pagebeforehide": "_handlePageBeforeHide"
9975 _handlePageBeforeShow: function() {
9976 var o = this.options;
9977 if ( o.disablePageZoom ) {
9978 $.mobile.zoom.disable( true );
9980 if ( !o.visibleOnPageShow ) {
9985 _handleAnimationStart: function() {
9986 if ( this.options.updatePagePadding ) {
9987 this.updatePagePadding( this._thisPage );
9991 _handlePageShow: function() {
9992 this.updatePagePadding( this._thisPage );
9993 if ( this.options.updatePagePadding ) {
9994 this._on( $.mobile.window, { "throttledresize": "updatePagePadding" } );
9998 _handlePageBeforeHide: function( e, ui ) {
9999 var o = this.options;
10001 if ( o.disablePageZoom ) {
10002 $.mobile.zoom.enable( true );
10004 if ( o.updatePagePadding ) {
10005 this._off( $.mobile.window, "throttledresize" );
10008 if ( o.trackPersistentToolbars ) {
10009 var thisFooter = $( ".ui-footer-fixed:jqmData(id)", this._thisPage ),
10010 thisHeader = $( ".ui-header-fixed:jqmData(id)", this._thisPage ),
10011 nextFooter = thisFooter.length && ui.nextPage && $( ".ui-footer-fixed:jqmData(id='" + thisFooter.jqmData( "id" ) + "')", ui.nextPage ) || $(),
10012 nextHeader = thisHeader.length && ui.nextPage && $( ".ui-header-fixed:jqmData(id='" + thisHeader.jqmData( "id" ) + "')", ui.nextPage ) || $();
10014 if ( nextFooter.length || nextHeader.length ) {
10016 nextFooter.add( nextHeader ).appendTo( $.mobile.pageContainer );
10018 ui.nextPage.one( "pageshow", function() {
10019 nextHeader.prependTo( this );
10020 nextFooter.appendTo( this );
10028 // This will set the content element's top or bottom padding equal to the toolbar's height
10029 updatePagePadding: function( tbPage ) {
10030 var $el = this.element,
10031 header = $el.is( ".ui-header" ),
10032 pos = parseFloat( $el.css( header ? "top" : "bottom" ) );
10034 // This behavior only applies to "fixed", not "fullscreen"
10035 if ( this.options.fullscreen ) { return; }
10037 // tbPage argument can be a Page object or an event, if coming from throttled resize.
10038 tbPage = ( tbPage && tbPage.type === undefined && tbPage ) || this._thisPage || $el.closest( ".ui-page" );
10039 $( tbPage ).css( "padding-" + ( header ? "top" : "bottom" ), $el.outerHeight() + pos );
10042 _useTransition: function( notransition ) {
10043 var $win = $.mobile.window,
10044 $el = this.element,
10045 scroll = $win.scrollTop(),
10046 elHeight = $el.height(),
10047 pHeight = $el.closest( ".ui-page" ).height(),
10048 viewportHeight = $.mobile.getScreenHeight(),
10049 tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer";
10051 return !notransition &&
10052 ( this.options.transition && this.options.transition !== "none" &&
10054 ( tbtype === "header" && !this.options.fullscreen && scroll > elHeight ) ||
10055 ( tbtype === "footer" && !this.options.fullscreen && scroll + viewportHeight < pHeight - elHeight )
10056 ) || this.options.fullscreen
10060 show: function( notransition ) {
10061 var hideClass = "ui-fixed-hidden",
10062 $el = this.element;
10064 if ( this._useTransition( notransition ) ) {
10066 .removeClass( "out " + hideClass )
10068 .animationComplete(function () {
10069 $el.removeClass('in');
10073 $el.removeClass( hideClass );
10075 this._visible = true;
10078 hide: function( notransition ) {
10079 var hideClass = "ui-fixed-hidden",
10080 $el = this.element,
10081 // if it's a slide transition, our new transitions need the reverse class as well to slide outward
10082 outclass = "out" + ( this.options.transition === "slide" ? " reverse" : "" );
10084 if( this._useTransition( notransition ) ) {
10086 .addClass( outclass )
10087 .removeClass( "in" )
10088 .animationComplete(function() {
10089 $el.addClass( hideClass ).removeClass( outclass );
10093 $el.addClass( hideClass ).removeClass( outclass );
10095 this._visible = false;
10098 toggle: function() {
10099 this[ this._visible ? "hide" : "show" ]();
10102 _bindToggleHandlers: function() {
10105 $el = self.element,
10106 delayShow, delayHide,
10110 $el.closest( ".ui-page" )
10111 .bind( "vclick", function( e ) {
10112 if ( o.tapToggle && !$( e.target ).closest( o.tapToggleBlacklist ).length ) {
10116 .bind( "focusin focusout", function( e ) {
10117 //this hides the toolbars on a keyboard pop to give more screen room and prevent ios bug which
10118 //positions fixed toolbars in the middle of the screen on pop if the input is near the top or
10119 //bottom of the screen addresses issues #4410 Footer navbar moves up when clicking on a textbox in an Android environment
10120 //and issue #4113 Header and footer change their position after keyboard popup - iOS
10121 //and issue #4410 Footer navbar moves up when clicking on a textbox in an Android environment
10122 if ( screen.width < 1025 && $( e.target ).is( o.hideDuringFocus ) && !$( e.target ).closest( ".ui-header-fixed, .ui-footer-fixed" ).length ) {
10123 //Fix for issue #4724 Moving through form in Mobile Safari with "Next" and "Previous" system
10124 //controls causes fixed position, tap-toggle false Header to reveal itself
10125 // isVisible instead of self._visible because the focusin and focusout events fire twice at the same time
10126 // Also use a delay for hiding the toolbars because on Android native browser focusin is direclty followed
10127 // by a focusout when a native selects opens and the other way around when it closes.
10128 if ( e.type === "focusout" && !isVisible ) {
10130 //wait for the stack to unwind and see if we have jumped to another input
10131 clearTimeout( delayHide );
10132 delayShow = setTimeout( function() {
10135 } else if ( e.type === "focusin" && !!isVisible ) {
10136 //if we have jumped to another input clear the time out to cancel the show.
10137 clearTimeout( delayShow );
10139 delayHide = setTimeout( function() {
10147 _destroy: function() {
10148 var $el = this.element,
10149 header = $el.is( ".ui-header" );
10151 $el.closest( ".ui-page" ).css( "padding-" + ( header ? "top" : "bottom" ), "" );
10152 $el.removeClass( "ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden" );
10153 $el.closest( ".ui-page" ).removeClass( "ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen" );
10158 //auto self-init widgets
10160 .bind( "pagecreate create", function( e ) {
10162 // DEPRECATED in 1.1: support for data-fullscreen=true|false on the page element.
10163 // This line ensures it still works, but we recommend moving the attribute to the toolbars themselves.
10164 if ( $( e.target ).jqmData( "fullscreen" ) ) {
10165 $( $.mobile.fixedtoolbar.prototype.options.initSelector, e.target ).not( ":jqmData(fullscreen)" ).jqmData( "fullscreen", true );
10168 $.mobile.fixedtoolbar.prototype.enhanceWithin( e.target );
10173 (function( $, undefined ) {
10174 $.widget( "mobile.fixedtoolbar", $.mobile.fixedtoolbar, {
10176 _create: function() {
10178 this._workarounds();
10181 //check the browser and version and run needed workarounds
10182 _workarounds: function() {
10183 var ua = navigator.userAgent,
10184 platform = navigator.platform,
10185 // Rendering engine is Webkit, and capture major version
10186 wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ),
10187 wkversion = !!wkmatch && wkmatch[ 1 ],
10190 //set the os we are working in if it dosent match one with workarounds return
10191 if( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ){
10193 } else if( ua.indexOf( "Android" ) > -1 ){
10198 //check os version if it dosent match one with workarounds return
10199 if( os === "ios" ) {
10201 self._bindScrollWorkaround();
10202 } else if( os === "android" && wkversion && wkversion < 534 ) {
10203 //Android 2.3 run all Android 2.3 workaround
10204 self._bindScrollWorkaround();
10205 self._bindListThumbWorkaround();
10211 //Utility class for checking header and footer positions relative to viewport
10212 _viewportOffset: function() {
10213 var $el = this.element,
10214 header = $el.is( ".ui-header" ),
10215 offset = Math.abs($el.offset().top - $.mobile.window.scrollTop());
10217 offset = Math.round(offset - $.mobile.window.height() + $el.outerHeight())-60;
10222 //bind events for _triggerRedraw() function
10223 _bindScrollWorkaround: function() {
10225 //bind to scrollstop and check if the toolbars are correctly positioned
10226 this._on( $.mobile.window, { scrollstop: function() {
10227 var viewportOffset = self._viewportOffset();
10228 //check if the header is visible and if its in the right place
10229 if( viewportOffset > 2 && self._visible) {
10230 self._triggerRedraw();
10235 //this addresses issue #4250 Persistent footer instability in v1.1 with long select lists in Android 2.3.3
10236 //and issue #3748 Android 2.x: Page transitions broken when fixed toolbars used
10237 //the absolutely positioned thumbnail in a list view causes problems with fixed position buttons above in a nav bar
10238 //setting the li's to -webkit-transform:translate3d(0,0,0); solves this problem to avoide potential issues in other
10239 //platforms we scope this with the class ui-android-2x-fix
10240 _bindListThumbWorkaround: function() {
10241 this.element.closest(".ui-page").addClass( "ui-android-2x-fixed" );
10243 //this addresses issues #4337 Fixed header problem after scrolling content on iOS and Android
10244 //and device bugs project issue #1 Form elements can lose click hit area in position: fixed containers.
10245 //this also addresses not on fixed toolbars page in docs
10246 //adding 1px of padding to the bottom then removing it causes a "redraw"
10247 //which positions the toolbars correctly (they will always be visually correct)
10248 _triggerRedraw: function() {
10249 var paddingBottom = parseFloat( $( ".ui-page-active" ).css( "padding-bottom" ) );
10250 //trigger page redraw to fix incorrectly positioned fixed elements
10251 $( ".ui-page-active" ).css( "padding-bottom", ( paddingBottom + 1 ) +"px" );
10252 //if the padding is reset with out a timeout the reposition will not occure.
10253 //this is independant of JQM the browser seems to need the time to react.
10254 setTimeout( function() {
10255 $( ".ui-page-active" ).css( "padding-bottom", paddingBottom + "px" );
10259 destroy: function() {
10261 //Remove the class we added to the page previously in android 2.x
10262 this.element.closest(".ui-page-active").removeClass( "ui-android-2x-fix" );
10268 (function( $, undefined ) {
10270 $.widget( "mobile.panel", $.mobile.widget, {
10274 panelOpen: "ui-panel-open",
10275 panelClosed: "ui-panel-closed",
10276 panelFixed: "ui-panel-fixed",
10277 panelInner: "ui-panel-inner",
10278 modal: "ui-panel-dismiss",
10279 modalOpen: "ui-panel-dismiss-open",
10280 pagePanel: "ui-page-panel",
10281 pagePanelOpen: "ui-page-panel-open",
10282 contentWrap: "ui-panel-content-wrap",
10283 contentWrapOpen: "ui-panel-content-wrap-open",
10284 contentWrapClosed: "ui-panel-content-wrap-closed",
10285 contentFixedToolbar: "ui-panel-content-fixed-toolbar",
10286 contentFixedToolbarOpen: "ui-panel-content-fixed-toolbar-open",
10287 contentFixedToolbarClosed: "ui-panel-content-fixed-toolbar-closed",
10288 animate: "ui-panel-animate"
10294 display: "reveal", //accepts reveal, push, overlay
10295 initSelector: ":jqmData(role='panel')",
10297 positionFixed: false
10306 _fixedToolbar: null,
10308 _create: function() {
10310 $el = self.element,
10311 page = $el.closest( ":jqmData(role='page')" ),
10312 _getPageTheme = function() {
10313 var $theme = $.data( page[0], "mobilePage" ).options.theme,
10314 $pageThemeClass = "ui-body-" + $theme;
10315 return $pageThemeClass;
10317 _getPanelInner = function() {
10318 var $panelInner = $el.find( "." + self.options.classes.panelInner );
10319 if ( $panelInner.length === 0 ) {
10320 $panelInner = $el.children().wrapAll( '<div class="' + self.options.classes.panelInner + '" />' ).parent();
10322 return $panelInner;
10324 _getWrapper = function() {
10325 var $wrapper = page.find( "." + self.options.classes.contentWrap );
10326 if ( $wrapper.length === 0 ) {
10327 $wrapper = page.children( ".ui-header:not(:jqmData(position='fixed')), .ui-content:not(:jqmData(role='popup')), .ui-footer:not(:jqmData(position='fixed'))" ).wrapAll( '<div class="' + self.options.classes.contentWrap + ' ' + _getPageTheme() + '" />' ).parent();
10328 if ( $.support.cssTransform3d && !!self.options.animate ) {
10329 $wrapper.addClass( self.options.classes.animate );
10334 _getFixedToolbar = function() {
10335 var $fixedToolbar = page.find( "." + self.options.classes.contentFixedToolbar );
10336 if ( $fixedToolbar.length === 0 ) {
10337 $fixedToolbar = page.find( ".ui-header:jqmData(position='fixed'), .ui-footer:jqmData(position='fixed')" ).addClass( self.options.classes.contentFixedToolbar );
10338 if ( $.support.cssTransform3d && !!self.options.animate ) {
10339 $fixedToolbar.addClass( self.options.classes.animate );
10342 return $fixedToolbar;
10345 // expose some private props to other methods
10347 _panelID: $el.attr( "id" ),
10348 _closeLink: $el.find( ":jqmData(rel='close')" ),
10349 _page: $el.closest( ":jqmData(role='page')" ),
10350 _pageTheme: _getPageTheme(),
10351 _panelInner: _getPanelInner(),
10352 _wrapper: _getWrapper(),
10353 _fixedToolbar: _getFixedToolbar()
10356 self._addPanelClasses();
10357 self._wrapper.addClass( this.options.classes.contentWrapClosed );
10358 self._fixedToolbar.addClass( this.options.classes.contentFixedToolbarClosed );
10359 // add class to page so we can set "overflow-x: hidden;" for it to fix Android zoom issue
10360 self._page.addClass( self.options.classes.pagePanel );
10362 // if animating, add the class to do so
10363 if ( $.support.cssTransform3d && !!self.options.animate ) {
10364 this.element.addClass( self.options.classes.animate );
10367 self._bindUpdateLayout();
10368 self._bindCloseEvents();
10369 self._bindLinkListeners();
10370 self._bindPageEvents();
10372 if ( !!self.options.dismissible ) {
10373 self._createModal();
10376 self._bindSwipeEvents();
10379 _createModal: function( options ) {
10382 self._modal = $( "<div class='" + self.options.classes.modal + "' data-panelid='" + self._panelID + "'></div>" )
10383 .on( "mousedown", function() {
10386 .appendTo( this._page );
10389 _getPosDisplayClasses: function( prefix ) {
10390 return prefix + "-position-" + this.options.position + " " + prefix + "-display-" + this.options.display;
10393 _getPanelClasses: function() {
10394 var panelClasses = this.options.classes.panel +
10395 " " + this._getPosDisplayClasses( this.options.classes.panel ) +
10396 " " + this.options.classes.panelClosed;
10398 if ( this.options.theme ) {
10399 panelClasses += " ui-body-" + this.options.theme;
10401 if ( !!this.options.positionFixed ) {
10402 panelClasses += " " + this.options.classes.panelFixed;
10404 return panelClasses;
10407 _addPanelClasses: function() {
10408 this.element.addClass( this._getPanelClasses() );
10411 _bindCloseEvents: function() {
10414 self._closeLink.on( "click.panel" , function( e ) {
10415 e.preventDefault();
10419 self.element.on( "click.panel" , "a:jqmData(ajax='false')", function( e ) {
10424 _positionPanel: function() {
10426 panelInnerHeight = self._panelInner.outerHeight(),
10427 expand = panelInnerHeight > $.mobile.getScreenHeight();
10429 if ( expand || !self.options.positionFixed ) {
10431 self._unfixPanel();
10432 $.mobile.resetActivePageHeight( panelInnerHeight );
10434 self._scrollIntoView( panelInnerHeight );
10440 _scrollIntoView: function( panelInnerHeight ) {
10441 if ( panelInnerHeight < $( window ).scrollTop() ) {
10442 window.scrollTo( 0, 0 );
10446 _bindFixListener: function() {
10447 this._on( $( window ), { "throttledresize": "_positionPanel" });
10450 _unbindFixListener: function() {
10451 this._off( $( window ), "throttledresize" );
10454 _unfixPanel: function() {
10455 if ( !!this.options.positionFixed && $.support.fixedPosition ) {
10456 this.element.removeClass( this.options.classes.panelFixed );
10460 _fixPanel: function() {
10461 if ( !!this.options.positionFixed && $.support.fixedPosition ) {
10462 this.element.addClass( this.options.classes.panelFixed );
10466 _bindUpdateLayout: function() {
10469 self.element.on( "updatelayout", function( e ) {
10470 if ( self._open ) {
10471 self._positionPanel();
10476 _bindLinkListeners: function() {
10479 self._page.on( "click.panel" , "a", function( e ) {
10480 if ( this.href.split( "#" )[ 1 ] === self._panelID && self._panelID !== undefined ) {
10481 e.preventDefault();
10482 var $link = $( this );
10483 if ( ! $link.hasClass( "ui-link" ) ) {
10484 $link.addClass( $.mobile.activeBtnClass );
10485 self.element.one( "panelopen panelclose", function() {
10486 $link.removeClass( $.mobile.activeBtnClass );
10495 _bindSwipeEvents: function() {
10497 area = self._modal ? self.element.add( self._modal ) : self.element;
10499 // on swipe, close the panel
10500 if( !!self.options.swipeClose ) {
10501 if ( self.options.position === "left" ) {
10502 area.on( "swipeleft.panel", function( e ) {
10506 area.on( "swiperight.panel", function( e ) {
10513 _bindPageEvents: function() {
10517 // Close the panel if another panel on the page opens
10518 .on( "panelbeforeopen", function( e ) {
10519 if ( self._open && e.target !== self.element[ 0 ] ) {
10523 // clean up open panels after page hide
10524 .on( "pagehide", function( e ) {
10525 if ( self._open ) {
10526 self.close( true );
10529 // on escape, close? might need to have a target check too...
10530 .on( "keyup.panel", function( e ) {
10531 if ( e.keyCode === 27 && self._open ) {
10537 // state storage of open or closed
10540 _contentWrapOpenClasses: null,
10541 _fixedToolbarOpenClasses: null,
10542 _modalOpenClasses: null,
10544 open: function( immediate ) {
10545 if ( !this._open ) {
10548 _openPanel = function() {
10549 self._page.off( "panelclose" );
10550 self._page.jqmData( "panel", "open" );
10552 if ( !immediate && $.support.cssTransform3d && !!o.animate ) {
10553 self.element.add( self._wrapper ).on( self._transitionEndEvents, complete );
10555 setTimeout( complete, 0 );
10558 if ( self.options.theme && self.options.display !== "overlay" ) {
10560 .removeClass( self._pageTheme )
10561 .addClass( "ui-body-" + self.options.theme );
10564 self.element.removeClass( o.classes.panelClosed ).addClass( o.classes.panelOpen );
10566 self._positionPanel();
10568 // Fix for IE7 min-height bug
10569 if ( self.options.theme && self.options.display !== "overlay" ) {
10570 self._wrapper.css( "min-height", self._page.css( "min-height" ) );
10573 self._contentWrapOpenClasses = self._getPosDisplayClasses( o.classes.contentWrap );
10575 .removeClass( o.classes.contentWrapClosed )
10576 .addClass( self._contentWrapOpenClasses + " " + o.classes.contentWrapOpen );
10578 self._fixedToolbarOpenClasses = self._getPosDisplayClasses( o.classes.contentFixedToolbar );
10580 .removeClass( o.classes.contentFixedToolbarClosed )
10581 .addClass( self._fixedToolbarOpenClasses + " " + o.classes.contentFixedToolbarOpen );
10583 self._modalOpenClasses = self._getPosDisplayClasses( o.classes.modal ) + " " + o.classes.modalOpen;
10584 if ( self._modal ) {
10585 self._modal.addClass( self._modalOpenClasses );
10588 complete = function() {
10589 self.element.add( self._wrapper ).off( self._transitionEndEvents, complete );
10591 self._page.addClass( o.classes.pagePanelOpen );
10593 self._bindFixListener();
10595 self._trigger( "open" );
10598 if ( this.element.closest( ".ui-page-active" ).length < 0 ) {
10602 self._trigger( "beforeopen" );
10604 if ( self._page.jqmData('panel') === "open" ) {
10605 self._page.on( "panelclose", function() {
10616 close: function( immediate ) {
10617 if ( this._open ) {
10618 var o = this.options,
10620 _closePanel = function() {
10621 if ( !immediate && $.support.cssTransform3d && !!o.animate ) {
10622 self.element.add( self._wrapper ).on( self._transitionEndEvents, complete );
10624 setTimeout( complete, 0 );
10627 self._page.removeClass( o.classes.pagePanelOpen );
10628 self.element.removeClass( o.classes.panelOpen );
10629 self._wrapper.removeClass( o.classes.contentWrapOpen );
10630 self._fixedToolbar.removeClass( o.classes.contentFixedToolbarOpen );
10632 if ( self._modal ) {
10633 self._modal.removeClass( self._modalOpenClasses );
10636 complete = function() {
10637 if ( self.options.theme && self.options.display !== "overlay" ) {
10638 self._page.removeClass( "ui-body-" + self.options.theme ).addClass( self._pageTheme );
10639 // reset fix for IE7 min-height bug
10640 self._wrapper.css( "min-height", "" );
10642 self.element.add( self._wrapper ).off( self._transitionEndEvents, complete );
10643 self.element.addClass( o.classes.panelClosed );
10646 .removeClass( self._contentWrapOpenClasses )
10647 .addClass( o.classes.contentWrapClosed );
10650 .removeClass( self._fixedToolbarOpenClasses )
10651 .addClass( o.classes.contentFixedToolbarClosed );
10654 self._unbindFixListener();
10655 $.mobile.resetActivePageHeight();
10657 self._page.jqmRemoveData( "panel" );
10658 self._trigger( "close" );
10661 if ( this.element.closest( ".ui-page-active" ).length < 0 ) {
10664 self._trigger( "beforeclose" );
10668 self._open = false;
10672 toggle: function( options ) {
10673 this[ this._open ? "close" : "open" ]();
10676 _transitionEndEvents: "webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd",
10678 _destroy: function() {
10679 var classes = this.options.classes,
10680 theme = this.options.theme,
10681 hasOtherSiblingPanels = this.element.siblings( "." + classes.panel ).length;
10684 if ( !hasOtherSiblingPanels ) {
10685 this._wrapper.children().unwrap();
10686 this._page.find( "a" ).unbind( "panelopen panelclose" );
10687 this._page.removeClass( classes.pagePanel );
10688 if ( this._open ) {
10689 this._page.jqmRemoveData( "panel" );
10690 this._page.removeClass( classes.pagePanelOpen );
10692 this._page.removeClass( "ui-body-" + theme ).addClass( this._pageTheme );
10694 $.mobile.resetActivePageHeight();
10696 } else if ( this._open ) {
10697 this._wrapper.removeClass( classes.contentWrapOpen );
10698 this._fixedToolbar.removeClass( classes.contentFixedToolbarOpen );
10699 this._page.jqmRemoveData( "panel" );
10700 this._page.removeClass( classes.pagePanelOpen );
10702 this._page.removeClass( "ui-body-" + theme ).addClass( this._pageTheme );
10706 this._panelInner.children().unwrap();
10708 this.element.removeClass( [ this._getPanelClasses(), classes.panelAnimate ].join( " " ) )
10709 .off( "swipeleft.panel swiperight.panel" )
10710 .off( "panelbeforeopen" )
10711 .off( "panelhide" )
10712 .off( "keyup.panel" )
10713 .off( "updatelayout" );
10715 this._closeLink.off( "click.panel" );
10717 if ( this._modal ) {
10718 this._modal.remove();
10722 this.element.off( this._transitionEndEvents )
10723 .removeClass( [ classes.panelUnfixed, classes.panelClosed, classes.panelOpen ].join( " " ) );
10727 //auto self-init widgets
10728 $( document ).bind( "pagecreate create", function( e ) {
10729 $.mobile.panel.prototype.enhanceWithin( e.target );
10734 (function( $, undefined ) {
10736 $.widget( "mobile.table", $.mobile.widget, {
10742 initSelector: ":jqmData(role='table')"
10745 _create: function() {
10747 self.refresh( true );
10750 refresh: function (create) {
10752 trs = this.element.find( "thead tr" );
10755 this.element.addClass( this.options.classes.table );
10758 // Expose headers and allHeaders properties on the widget
10759 // headers references the THs within the first TR in the table
10760 self.headers = this.element.find( "tr:eq(0)" ).children();
10762 // allHeaders references headers, plus all THs in the thead, which may include several rows, or not
10763 self.allHeaders = self.headers.add( trs.children() );
10765 trs.each(function(){
10769 $( this ).children().each(function( i ){
10771 var span = parseInt( $( this ).attr( "colspan" ), 10 ),
10772 sel = ":nth-child(" + ( coltally + 1 ) + ")";
10774 .jqmData( "colstart", coltally + 1 );
10777 for( var j = 0; j < span - 1; j++ ){
10779 sel += ", :nth-child(" + ( coltally + 1 ) + ")";
10783 if ( create === undefined ) {
10784 $(this).jqmData("cells", "");
10786 // Store "cells" data on header as a reference to all cells in the same column as this TH
10788 .jqmData( "cells", self.element.find( "tr" ).not( trs.eq(0) ).not( this ).children( sel ) );
10796 // update table modes
10797 if ( create === undefined ) {
10798 this.element.trigger( 'refresh' );
10804 //auto self-init widgets
10805 $.mobile.document.bind( "pagecreate create", function( e ) {
10806 $.mobile.table.prototype.enhanceWithin( e.target );
10812 (function( $, undefined ) {
10814 $.mobile.table.prototype.options.mode = "columntoggle";
10816 $.mobile.table.prototype.options.columnBtnTheme = null;
10818 $.mobile.table.prototype.options.columnPopupTheme = null;
10820 $.mobile.table.prototype.options.columnBtnText = "Columns...";
10822 $.mobile.table.prototype.options.classes = $.extend(
10823 $.mobile.table.prototype.options.classes,
10825 popup: "ui-table-columntoggle-popup",
10826 columnBtn: "ui-table-columntoggle-btn",
10827 priorityPrefix: "ui-table-priority-",
10828 columnToggleTable: "ui-table-columntoggle"
10832 $.mobile.document.delegate( ":jqmData(role='table')", "tablecreate refresh", function( e ) {
10834 var $table = $( this ),
10835 self = $table.data( "mobile-table" ),
10839 id = ( $table.attr( "id" ) || o.classes.popup ) + "-popup", /* TODO BETTER FALLBACK ID HERE */
10845 if ( o.mode !== "columntoggle" ) {
10849 if ( event !== "refresh" ) {
10850 self.element.addClass( o.classes.columnToggleTable );
10852 $menuButton = $( "<a href='#" + id + "' class='" + o.classes.columnBtn + "' data-" + ns + "rel='popup' data-" + ns + "mini='true'>" + o.columnBtnText + "</a>" ),
10853 $popup = $( "<div data-" + ns + "role='popup' data-" + ns + "role='fieldcontain' class='" + o.classes.popup + "' id='" + id + "'></div>"),
10854 $menu = $("<fieldset data-" + ns + "role='controlgroup'></fieldset>");
10857 // create the hide/show toggles
10858 self.headers.not( "td" ).each(function( i ) {
10860 var priority = $( this ).jqmData( "priority" ),
10861 $cells = $( this ).add( $( this ).jqmData( "cells" ) );
10865 $cells.addClass( o.classes.priorityPrefix + priority );
10867 if ( event !== "refresh" ) {
10868 $("<label><input type='checkbox' checked />" + $( this ).text() + "</label>" )
10871 .jqmData( "cells", $cells )
10873 theme: o.columnPopupTheme
10876 $( '#' + id + ' fieldset div:eq(' + i +')').find('input').jqmData( 'cells', $cells );
10881 if ( event !== "refresh" ) {
10882 $menu.appendTo( $popup );
10885 // bind change event listeners to inputs - TODO: move to a private method?
10886 if ( $menu === undefined ) {
10887 $switchboard = $('#' + id + ' fieldset');
10889 $switchboard = $menu;
10892 if ( event !== "refresh" ) {
10893 $switchboard.on( "change", "input", function( e ){
10894 if( this.checked ){
10895 $( this ).jqmData( "cells" ).removeClass( "ui-table-cell-hidden" ).addClass( "ui-table-cell-visible" );
10897 $( this ).jqmData( "cells" ).removeClass( "ui-table-cell-visible" ).addClass( "ui-table-cell-hidden" );
10902 .insertBefore( $table )
10904 theme: o.columnBtnTheme
10908 .insertBefore( $table )
10913 self.update = function(){
10914 $switchboard.find( "input" ).each( function(){
10915 if (this.checked) {
10916 this.checked = $( this ).jqmData( "cells" ).eq(0).css( "display" ) === "table-cell";
10917 if (event === "refresh") {
10918 $( this ).jqmData( "cells" ).addClass('ui-table-cell-visible');
10921 $( this ).jqmData( "cells" ).addClass('ui-table-cell-hidden');
10923 $( this ).checkboxradio( "refresh" );
10927 $.mobile.window.on( "throttledresize", self.update );
10935 (function( $, undefined ) {
10937 $.mobile.table.prototype.options.mode = "reflow";
10939 $.mobile.table.prototype.options.classes = $.extend(
10940 $.mobile.table.prototype.options.classes,
10942 reflowTable: "ui-table-reflow",
10943 cellLabels: "ui-table-cell-label"
10947 $.mobile.document.delegate( ":jqmData(role='table')", "tablecreate refresh", function( e ) {
10949 var $table = $( this ),
10951 self = $table.data( "mobile-table" ),
10954 // If it's not reflow mode, return here.
10955 if( o.mode !== "reflow" ){
10959 if ( event !== "refresh" ) {
10960 self.element.addClass( o.classes.reflowTable );
10963 // get headers in reverse order so that top-level headers are appended last
10964 var reverseHeaders = $( self.allHeaders.get().reverse() );
10966 // create the hide/show toggles
10967 reverseHeaders.each(function( i ){
10968 var $cells = $( this ).jqmData( "cells" ),
10969 colstart = $( this ).jqmData( "colstart" ),
10970 hierarchyClass = $cells.not( this ).filter( "thead th" ).length && " ui-table-cell-label-top",
10971 text = $(this).text();
10975 if( hierarchyClass ){
10976 var iteration = parseInt( $( this ).attr( "colspan" ), 10 ),
10980 filter = "td:nth-child("+ iteration +"n + " + ( colstart ) +")";
10982 $cells.filter( filter ).prepend( "<b class='" + o.classes.cellLabels + hierarchyClass + "'>" + text + "</b>" );
10985 $cells.prepend( "<b class='" + o.classes.cellLabels + "'>" + text + "</b>" );
10995 (function( $, window ) {
10997 $.mobile.iosorientationfixEnabled = true;
10999 // This fix addresses an iOS bug, so return early if the UA claims it's something else.
11000 var ua = navigator.userAgent;
11001 if( !( /iPhone|iPad|iPod/.test( navigator.platform ) && /OS [1-5]_[0-9_]* like Mac OS X/i.test( ua ) && ua.indexOf( "AppleWebKit" ) > -1 ) ){
11002 $.mobile.iosorientationfixEnabled = false;
11006 var zoom = $.mobile.zoom,
11009 function checkTilt( e ) {
11010 evt = e.originalEvent;
11011 aig = evt.accelerationIncludingGravity;
11013 x = Math.abs( aig.x );
11014 y = Math.abs( aig.y );
11015 z = Math.abs( aig.z );
11017 // If portrait orientation and in one of the danger zones
11018 if ( !window.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ) {
11019 if ( zoom.enabled ) {
11022 } else if ( !zoom.enabled ) {
11027 $.mobile.document.on( "mobileinit", function(){
11028 if( $.mobile.iosorientationfixEnabled ){
11030 .bind( "orientationchange.iosorientationfix", zoom.enable )
11031 .bind( "devicemotion.iosorientationfix", checkTilt );
11035 }( jQuery, this ));
11037 (function( $, window, undefined ) {
11038 var $html = $( "html" ),
11039 $head = $( "head" ),
11040 $window = $.mobile.window;
11042 //remove initial build class (only present on first pageshow)
11043 function hideRenderingClass() {
11044 $html.removeClass( "ui-mobile-rendering" );
11047 // trigger mobileinit event - useful hook for configuring $.mobile settings before they're used
11048 $( window.document ).trigger( "mobileinit" );
11050 // support conditions
11051 // if device support condition(s) aren't met, leave things as they are -> a basic, usable experience,
11052 // otherwise, proceed with the enhancements
11053 if ( !$.mobile.gradeA() ) {
11057 // override ajaxEnabled on platforms that have known conflicts with hash history updates
11058 // or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini)
11059 if ( $.mobile.ajaxBlacklist ) {
11060 $.mobile.ajaxEnabled = false;
11063 // Add mobile, initial load "rendering" classes to docEl
11064 $html.addClass( "ui-mobile ui-mobile-rendering" );
11066 // This is a fallback. If anything goes wrong (JS errors, etc), or events don't fire,
11067 // this ensures the rendering class is removed after 5 seconds, so content is visible and accessible
11068 setTimeout( hideRenderingClass, 5000 );
11070 $.extend( $.mobile, {
11071 // find and enhance the pages in the dom and transition to the first page.
11072 initializePage: function() {
11073 // find present pages
11074 var path = $.mobile.path,
11075 $pages = $( ":jqmData(role='page'), :jqmData(role='dialog')" ),
11076 hash = path.stripHash( path.stripQueryParams(path.parseLocation().hash) ),
11077 hashPage = document.getElementById( hash );
11079 // if no pages are found, create one with body's inner html
11080 if ( !$pages.length ) {
11081 $pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 );
11084 // add dialogs, set data-url attrs
11085 $pages.each(function() {
11086 var $this = $( this );
11088 // unless the data url is already set set it to the pathname
11089 if ( !$this.jqmData( "url" ) ) {
11090 $this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) || location.pathname + location.search );
11094 // define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback)
11095 $.mobile.firstPage = $pages.first();
11097 // define page container
11098 $.mobile.pageContainer = $.mobile.firstPage.parent().addClass( "ui-mobile-viewport" );
11100 // alert listeners that the pagecontainer has been determined for binding
11101 // to events triggered on it
11102 $window.trigger( "pagecontainercreate" );
11104 // cue page loading message
11105 $.mobile.showPageLoadingMsg();
11107 //remove initial build class (only present on first pageshow)
11108 hideRenderingClass();
11110 // if hashchange listening is disabled, there's no hash deeplink,
11111 // the hash is not valid (contains more than one # or does not start with #)
11112 // or there is no page with that hash, change to the first page in the DOM
11113 // Remember, however, that the hash can also be a path!
11114 if ( ! ( $.mobile.hashListeningEnabled &&
11115 $.mobile.path.isHashValid( location.hash ) &&
11116 ( $( hashPage ).is( ':jqmData(role="page")' ) ||
11117 $.mobile.path.isPath( hash ) ||
11118 hash === $.mobile.dialogHashKey ) ) ) {
11120 // Store the initial destination
11121 if ( $.mobile.path.isHashValid( location.hash ) ) {
11122 $.mobile.urlHistory.initialDst = hash.replace( "#", "" );
11125 // make sure to set initial popstate state if it exists
11126 // so that navigation back to the initial page works properly
11127 if( $.event.special.navigate.isPushStateEnabled() ) {
11128 $.mobile.navigate.navigator.squash( path.parseLocation().href );
11131 $.mobile.changePage( $.mobile.firstPage, {
11132 transition: "none",
11135 fromHashChange: true
11138 // trigger hashchange or navigate to squash and record the correct
11139 // history entry for an initial hash path
11140 if( !$.event.special.navigate.isPushStateEnabled() ) {
11141 $window.trigger( "hashchange", [true] );
11143 // TODO figure out how to simplify this interaction with the initial history entry
11144 // at the bottom js/navigate/navigate.js
11145 $.mobile.navigate.history.stack = [];
11146 $.mobile.navigate( $.mobile.path.isPath( location.hash ) ? location.hash : location.href );
11152 // initialize events now, after mobileinit has occurred
11153 $.mobile.navreadyDeferred.resolve();
11155 // check which scrollTop value should be used by scrolling to 1 immediately at domready
11156 // then check what the scroll top is. Android will report 0... others 1
11157 // note that this initial scroll won't hide the address bar. It's just for the check.
11159 window.scrollTo( 0, 1 );
11161 // if defaultHomeScroll hasn't been set yet, see if scrollTop is 1
11162 // it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar)
11163 // so if it's 1, use 0 from now on
11164 $.mobile.defaultHomeScroll = ( !$.support.scrollTop || $.mobile.window.scrollTop() === 1 ) ? 0 : 1;
11167 if ( $.mobile.autoInitializePage ) {
11168 $.mobile.initializePage();
11171 // window load event
11172 // hide iOS browser chrome on load
11173 $window.load( $.mobile.silentScroll );
11175 if ( !$.support.cssPointerEvents ) {
11176 // IE and Opera don't support CSS pointer-events: none that we use to disable link-based buttons
11177 // by adding the 'ui-disabled' class to them. Using a JavaScript workaround for those browser.
11178 // https://github.com/jquery/jquery-mobile/issues/3558
11180 $.mobile.document.delegate( ".ui-disabled", "vclick",
11182 e.preventDefault();
11183 e.stopImmediatePropagation();
11188 }( jQuery, this ));