"auto"
: all undefined swipes will cause the page to scroll in that direction. "none"
: the page will not scroll when user swipes. "horizontal"
: will force page to scroll on horizontal swipes. "vertical"
: will force page to scroll on vertical swipes. method
is a TouchSwipe method, then
* the method
is executed, and any following arguments are passed to the TouchSwipe method.
* If method
is an object, then the TouchSwipe class is instantiated on the current DOMNode, passing the
* configuration properties defined in the object. See TouchSwipe
*
*/
$.fn.swipe = function (method) {
var $this = $(this),
plugin = $this.data(PLUGIN_NS);
//Check if we are already instantiated and trying to execute a method
if (plugin && typeof method === 'string') {
if (plugin[method]) {
return plugin[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else {
$.error('Method ' + method + ' does not exist on jQuery.swipe');
}
}
//Else update existing plugin with new options hash
else if (plugin && typeof method === 'object') {
plugin['option'].apply(this, arguments);
}
//Else not instantiated and trying to pass init object (or nothing)
else if (!plugin && (typeof method === 'object' || !method)) {
return init.apply(this, arguments);
}
return $this;
};
/**
* The version of the plugin
* @readonly
*/
$.fn.swipe.version = VERSION;
//Expose our defaults so a user could override the plugin defaults
$.fn.swipe.defaults = defaults;
/**
* The phases that a touch event goes through. The phase
is passed to the event handlers.
* These properties are read only, attempting to change them will not alter the values passed to the event handlers.
* @namespace
* @readonly
* @property {string} PHASE_START Constant indicating the start phase of the touch event. Value is "start"
.
* @property {string} PHASE_MOVE Constant indicating the move phase of the touch event. Value is "move"
.
* @property {string} PHASE_END Constant indicating the end phase of the touch event. Value is "end"
.
* @property {string} PHASE_CANCEL Constant indicating the cancel phase of the touch event. Value is "cancel"
.
*/
$.fn.swipe.phases = {
PHASE_START: PHASE_START,
PHASE_MOVE: PHASE_MOVE,
PHASE_END: PHASE_END,
PHASE_CANCEL: PHASE_CANCEL
};
/**
* The direction constants that are passed to the event handlers.
* These properties are read only, attempting to change them will not alter the values passed to the event handlers.
* @namespace
* @readonly
* @property {string} LEFT Constant indicating the left direction. Value is "left"
.
* @property {string} RIGHT Constant indicating the right direction. Value is "right"
.
* @property {string} UP Constant indicating the up direction. Value is "up"
.
* @property {string} DOWN Constant indicating the down direction. Value is "cancel"
.
* @property {string} IN Constant indicating the in direction. Value is "in"
.
* @property {string} OUT Constant indicating the out direction. Value is "out"
.
*/
$.fn.swipe.directions = {
LEFT: LEFT,
RIGHT: RIGHT,
UP: UP,
DOWN: DOWN,
IN : IN,
OUT: OUT
};
/**
* The page scroll constants that can be used to set the value of allowPageScroll
option
* These properties are read only
* @namespace
* @readonly
* @see $.fn.swipe.defaults#allowPageScroll
* @property {string} NONE Constant indicating no page scrolling is allowed. Value is "none"
.
* @property {string} HORIZONTAL Constant indicating horizontal page scrolling is allowed. Value is "horizontal"
.
* @property {string} VERTICAL Constant indicating vertical page scrolling is allowed. Value is "vertical"
.
* @property {string} AUTO Constant indicating either horizontal or vertical will be allowed, depending on the swipe handlers registered. Value is "auto"
.
*/
$.fn.swipe.pageScroll = {
NONE: NONE,
HORIZONTAL: HORIZONTAL,
VERTICAL: VERTICAL,
AUTO: AUTO
};
/**
* Constants representing the number of fingers used in a swipe. These are used to set both the value of fingers
in the
* options object, as well as the value of the fingers
event property.
* These properties are read only, attempting to change them will not alter the values passed to the event handlers.
* @namespace
* @readonly
* @see $.fn.swipe.defaults#fingers
* @property {string} ONE Constant indicating 1 finger is to be detected / was detected. Value is 1
.
* @property {string} TWO Constant indicating 2 fingers are to be detected / were detected. Value is 2
.
* @property {string} THREE Constant indicating 3 finger are to be detected / were detected. Value is 3
.
* @property {string} FOUR Constant indicating 4 finger are to be detected / were detected. Not all devices support this. Value is 4
.
* @property {string} FIVE Constant indicating 5 finger are to be detected / were detected. Not all devices support this. Value is 5
.
* @property {string} ALL Constant indicating any combination of finger are to be detected. Value is "all"
.
*/
$.fn.swipe.fingers = {
ONE: 1,
TWO: 2,
THREE: 3,
FOUR: 4,
FIVE: 5,
ALL: ALL_FINGERS
};
/**
* Initialise the plugin for each DOM element matched
* This creates a new instance of the main TouchSwipe class for each DOM element, and then
* saves a reference to that instance in the elements data property.
* @internal
*/
function init(options) {
//Prep and extend the options
if (options && (options.allowPageScroll === undefined && (options.swipe !== undefined || options.swipeStatus !== undefined))) {
options.allowPageScroll = NONE;
}
//Check for deprecated options
//Ensure that any old click handlers are assigned to the new tap, unless we have a tap
if(options.click!==undefined && options.tap===undefined) {
options.tap = options.click;
}
if (!options) {
options = {};
}
//pass empty object so we dont modify the defaults
options = $.extend({}, $.fn.swipe.defaults, options);
//For each element instantiate the plugin
return this.each(function () {
var $this = $(this);
//Check we havent already initialised the plugin
var plugin = $this.data(PLUGIN_NS);
if (!plugin) {
plugin = new TouchSwipe(this, options);
$this.data(PLUGIN_NS, plugin);
}
});
}
/**
* Main TouchSwipe Plugin Class.
* Do not use this to construct your TouchSwipe object, use the jQuery plugin method $.fn.swipe(); {@link $.fn.swipe}
* @private
* @name TouchSwipe
* @param {DOMNode} element The HTML DOM object to apply to plugin to
* @param {Object} options The options to configure the plugin with. @link {$.fn.swipe.defaults}
* @see $.fh.swipe.defaults
* @see $.fh.swipe
* @class
*/
function TouchSwipe(element, options) {
//take a local/instacne level copy of the options - should make it this.options really...
var options = $.extend({}, options);
var useTouchEvents = (SUPPORTS_TOUCH || SUPPORTS_POINTER || !options.fallbackToMouseEvents),
START_EV = useTouchEvents ? (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerDown' : 'pointerdown') : 'touchstart') : 'mousedown',
MOVE_EV = useTouchEvents ? (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerMove' : 'pointermove') : 'touchmove') : 'mousemove',
END_EV = useTouchEvents ? (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerUp' : 'pointerup') : 'touchend') : 'mouseup',
LEAVE_EV = useTouchEvents ? null : 'mouseleave', //we manually detect leave on touch devices, so null event here
CANCEL_EV = (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerCancel' : 'pointercancel') : 'touchcancel');
//touch properties
var distance = 0,
direction = null,
duration = 0,
startTouchesDistance = 0,
endTouchesDistance = 0,
pinchZoom = 1,
pinchDistance = 0,
pinchDirection = 0,
maximumsMap=null;
//jQuery wrapped element for this instance
var $element = $(element);
//Current phase of th touch cycle
var phase = "start";
// the current number of fingers being used.
var fingerCount = 0;
//track mouse points / delta
var fingerData = {};
//track times
var startTime = 0,
endTime = 0,
previousTouchEndTime=0,
fingerCountAtRelease=0,
doubleTapStartTime=0;
//Timeouts
var singleTapTimeout=null,
holdTimeout=null;
// Add gestures to all swipable areas if supported
try {
$element.bind(START_EV, touchStart);
$element.bind(CANCEL_EV, touchCancel);
}
catch (e) {
$.error('events not supported ' + START_EV + ',' + CANCEL_EV + ' on jQuery.swipe');
}
//
//Public methods
//
/**
* re-enables the swipe plugin with the previous configuration
* @function
* @name $.fn.swipe#enable
* @return {DOMNode} The Dom element that was registered with TouchSwipe
* @example $("#element").swipe("enable");
*/
this.enable = function () {
$element.bind(START_EV, touchStart);
$element.bind(CANCEL_EV, touchCancel);
return $element;
};
/**
* disables the swipe plugin
* @function
* @name $.fn.swipe#disable
* @return {DOMNode} The Dom element that is now registered with TouchSwipe
* @example $("#element").swipe("disable");
*/
this.disable = function () {
removeListeners();
return $element;
};
/**
* Destroy the swipe plugin completely. To use any swipe methods, you must re initialise the plugin.
* @function
* @name $.fn.swipe#destroy
* @example $("#element").swipe("destroy");
*/
this.destroy = function () {
removeListeners();
$element.data(PLUGIN_NS, null);
$element = null;
};
/**
* Allows run time updating of the swipe configuration options.
* @function
* @name $.fn.swipe#option
* @param {String} property The option property to get or set, or a has of multiple options to set
* @param {Object} [value] The value to set the property to
* @return {Object} If only a property name is passed, then that property value is returned. If nothing is passed the current options hash is returned.
* @example $("#element").swipe("option", "threshold"); // return the threshold
* @example $("#element").swipe("option", "threshold", 100); // set the threshold after init
* @example $("#element").swipe("option", {threshold:100, fingers:3} ); // set multiple properties after init
* @example $("#element").swipe({threshold:100, fingers:3} ); // set multiple properties after init - the "option" method is optional!
* @example $("#element").swipe("option"); // Return the current options hash
* @see $.fn.swipe.defaults
*
*/
this.option = function (property, value) {
if(typeof property === 'object') {
options = $.extend(options, property);
} else if(options[property]!==undefined) {
if(value===undefined) {
return options[property];
} else {
options[property] = value;
}
} else if (!property) {
return options;
} else {
$.error('Option ' + property + ' does not exist on jQuery.swipe.options');
}
return null;
}
//
// Private methods
//
//
// EVENTS
//
/**
* Event handler for a touch start event.
* Stops the default click event from triggering and stores where we touched
* @inner
* @param {object} jqEvent The normalised jQuery event object.
*/
function touchStart(jqEvent) {
//If we already in a touch event (a finger already in use) then ignore subsequent ones..
if( getTouchInProgress() )
return;
//Check if this element matches any in the excluded elements selectors, or its parent is excluded, if so, DON'T swipe
if( $(jqEvent.target).closest( options.excludedElements, $element ).length>0 )
return;
//As we use Jquery bind for events, we need to target the original event object
//If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent;
var ret,
touches = event.touches,
evt = touches ? touches[0] : event;
phase = PHASE_START;
//If we support touches, get the finger count
if (touches) {
// get the total number of fingers touching the screen
fingerCount = touches.length;
}
//Else this is the desktop, so stop the browser from dragging content
else if(options.preventDefaultEvents !== false) {
jqEvent.preventDefault(); //call this on jq event so we are cross browser
}
//clear vars..
distance = 0;
direction = null;
pinchDirection=null;
duration = 0;
startTouchesDistance=0;
endTouchesDistance=0;
pinchZoom = 1;
pinchDistance = 0;
maximumsMap=createMaximumsData();
cancelMultiFingerRelease();
//Create the default finger data
createFingerData( 0, evt );
// check the number of fingers is what we are looking for, or we are capturing pinches
if (!touches || (fingerCount === options.fingers || options.fingers === ALL_FINGERS) || hasPinches()) {
// get the coordinates of the touch
startTime = getTimeStamp();
if(fingerCount==2) {
//Keep track of the initial pinch distance, so we can calculate the diff later
//Store second finger data as start
createFingerData( 1, touches[1] );
startTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start);
}
if (options.swipeStatus || options.pinchStatus) {
ret = triggerHandler(event, phase);
}
}
else {
//A touch with more or less than the fingers we are looking for, so cancel
ret = false;
}
//If we have a return value from the users handler, then return and cancel
if (ret === false) {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
return ret;
}
else {
if (options.hold) {
holdTimeout = setTimeout($.proxy(function() {
//Trigger the event
$element.trigger('hold', [event.target]);
//Fire the callback
if(options.hold) {
ret = options.hold.call($element, event, event.target);
}
}, this), options.longTapThreshold );
}
setTouchInProgress(true);
}
return null;
};
/**
* Event handler for a touch move event.
* If we change fingers during move, then cancel the event
* @inner
* @param {object} jqEvent The normalised jQuery event object.
*/
function touchMove(jqEvent) {
//As we use Jquery bind for events, we need to target the original event object
//If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent;
//If we are ending, cancelling, or within the threshold of 2 fingers being released, don't track anything..
if (phase === PHASE_END || phase === PHASE_CANCEL || inMultiFingerRelease())
return;
var ret,
touches = event.touches,
evt = touches ? touches[0] : event;
//Update the finger data
var currentFinger = updateFingerData(evt);
endTime = getTimeStamp();
if (touches) {
fingerCount = touches.length;
}
if (options.hold)
clearTimeout(holdTimeout);
phase = PHASE_MOVE;
//If we have 2 fingers get Touches distance as well
if(fingerCount==2) {
//Keep track of the initial pinch distance, so we can calculate the diff later
//We do this here as well as the start event, in case they start with 1 finger, and the press 2 fingers
if(startTouchesDistance==0) {
//Create second finger if this is the first time...
createFingerData( 1, touches[1] );
startTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start);
} else {
//Else just update the second finger
updateFingerData(touches[1]);
endTouchesDistance = calculateTouchesDistance(fingerData[0].end, fingerData[1].end);
pinchDirection = calculatePinchDirection(fingerData[0].end, fingerData[1].end);
}
pinchZoom = calculatePinchZoom(startTouchesDistance, endTouchesDistance);
pinchDistance = Math.abs(startTouchesDistance - endTouchesDistance);
}
if ( (fingerCount === options.fingers || options.fingers === ALL_FINGERS) || !touches || hasPinches() ) {
direction = calculateDirection(currentFinger.start, currentFinger.end);
//Check if we need to prevent default event (page scroll / pinch zoom) or not
validateDefaultEvent(jqEvent, direction);
//Distance and duration are all off the main finger
distance = calculateDistance(currentFinger.start, currentFinger.end);
duration = calculateDuration();
//Cache the maximum distance we made in this direction
setMaxDistance(direction, distance);
if (options.swipeStatus || options.pinchStatus) {
ret = triggerHandler(event, phase);
}
//If we trigger end events when threshold are met, or trigger events when touch leaves element
if(!options.triggerOnTouchEnd || options.triggerOnTouchLeave) {
var inBounds = true;
//If checking if we leave the element, run the bounds check (we can use touchleave as its not supported on webkit)
if(options.triggerOnTouchLeave) {
var bounds = getbounds( this );
inBounds = isInBounds( currentFinger.end, bounds );
}
//Trigger end handles as we swipe if thresholds met or if we have left the element if the user has asked to check these..
if(!options.triggerOnTouchEnd && inBounds) {
phase = getNextPhase( PHASE_MOVE );
}
//We end if out of bounds here, so set current phase to END, and check if its modified
else if(options.triggerOnTouchLeave && !inBounds ) {
phase = getNextPhase( PHASE_END );
}
if(phase==PHASE_CANCEL || phase==PHASE_END) {
triggerHandler(event, phase);
}
}
}
else {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
}
if (ret === false) {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
}
}
/**
* Event handler for a touch end event.
* Calculate the direction and trigger events
* @inner
* @param {object} jqEvent The normalised jQuery event object.
*/
function touchEnd(jqEvent) {
//As we use Jquery bind for events, we need to target the original event object
//If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent,
touches = event.touches;
//If we are still in a touch with the device wait a fraction and see if the other finger comes up
//if it does within the threshold, then we treat it as a multi release, not a single release and end the touch / swipe
if (touches) {
if(touches.length && !inMultiFingerRelease()) {
startMultiFingerRelease();
return true;
} else if (touches.length && inMultiFingerRelease()) {
return true;
}
}
//If a previous finger has been released, check how long ago, if within the threshold, then assume it was a multifinger release.
//This is used to allow 2 fingers to release fractionally after each other, whilst maintainig the event as containg 2 fingers, not 1
if(inMultiFingerRelease()) {
fingerCount=fingerCountAtRelease;
}
//Set end of swipe
endTime = getTimeStamp();
//Get duration incase move was never fired
duration = calculateDuration();
//If we trigger handlers at end of swipe OR, we trigger during, but they didnt trigger and we are still in the move phase
if(didSwipeBackToCancel() || !validateSwipeDistance()) {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
} else if (options.triggerOnTouchEnd || (options.triggerOnTouchEnd == false && phase === PHASE_MOVE)) {
//call this on jq event so we are cross browser
if(options.preventDefaultEvents !== false) {
jqEvent.preventDefault();
}
phase = PHASE_END;
triggerHandler(event, phase);
}
//Special cases - A tap should always fire on touch end regardless,
//So here we manually trigger the tap end handler by itself
//We dont run trigger handler as it will re-trigger events that may have fired already
else if (!options.triggerOnTouchEnd && hasTap()) {
//Trigger the pinch events...
phase = PHASE_END;
triggerHandlerForGesture(event, phase, TAP);
}
else if (phase === PHASE_MOVE) {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
}
setTouchInProgress(false);
return null;
}
/**
* Event handler for a touch cancel event.
* Clears current vars
* @inner
*/
function touchCancel() {
// reset the variables back to default values
fingerCount = 0;
endTime = 0;
startTime = 0;
startTouchesDistance=0;
endTouchesDistance=0;
pinchZoom=1;
//If we were in progress of tracking a possible multi touch end, then re set it.
cancelMultiFingerRelease();
setTouchInProgress(false);
}
/**
* Event handler for a touch leave event.
* This is only triggered on desktops, in touch we work this out manually
* as the touchleave event is not supported in webkit
* @inner
*/
function touchLeave(jqEvent) {
//If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent;
//If we have the trigger on leave property set....
if(options.triggerOnTouchLeave) {
phase = getNextPhase( PHASE_END );
triggerHandler(event, phase);
}
}
/**
* Removes all listeners that were associated with the plugin
* @inner
*/
function removeListeners() {
$element.unbind(START_EV, touchStart);
$element.unbind(CANCEL_EV, touchCancel);
$element.unbind(MOVE_EV, touchMove);
$element.unbind(END_EV, touchEnd);
//we only have leave events on desktop, we manually calculate leave on touch as its not supported in webkit
if(LEAVE_EV) {
$element.unbind(LEAVE_EV, touchLeave);
}
setTouchInProgress(false);
}
/**
* Checks if the time and distance thresholds have been met, and if so then the appropriate handlers are fired.
*/
function getNextPhase(currentPhase) {
var nextPhase = currentPhase;
// Ensure we have valid swipe (under time and over distance and check if we are out of bound...)
var validTime = validateSwipeTime();
var validDistance = validateSwipeDistance();
var didCancel = didSwipeBackToCancel();
//If we have exceeded our time, then cancel
if(!validTime || didCancel) {
nextPhase = PHASE_CANCEL;
}
//Else if we are moving, and have reached distance then end
else if (validDistance && currentPhase == PHASE_MOVE && (!options.triggerOnTouchEnd || options.triggerOnTouchLeave) ) {
nextPhase = PHASE_END;
}
//Else if we have ended by leaving and didn't reach distance, then cancel
else if (!validDistance && currentPhase==PHASE_END && options.triggerOnTouchLeave) {
nextPhase = PHASE_CANCEL;
}
return nextPhase;
}
/**
* Trigger the relevant event handler
* The handlers are passed the original event, the element that was swiped, and in the case of the catch all handler, the direction that was swiped, "left", "right", "up", or "down"
* @param {object} event the original event object
* @param {string} phase the phase of the swipe (start, end cancel etc) {@link $.fn.swipe.phases}
* @inner
*/
function triggerHandler(event, phase) {
var ret,
touches = event.touches;
//Swipes and pinches are not mutually exclusive - can happend at same time, so need to trigger 2 events potentially
if( (didSwipe() && hasSwipes()) || (didPinch() && hasPinches()) ) {
// SWIPE GESTURES
if(didSwipe() && hasSwipes()) { //hasSwipes as status needs to fire even if swipe is invalid
//Trigger the swipe events...
ret = triggerHandlerForGesture(event, phase, SWIPE);
}
// PINCH GESTURES (if the above didn't cancel)
if((didPinch() && hasPinches()) && ret!==false) {
//Trigger the pinch events...
ret = triggerHandlerForGesture(event, phase, PINCH);
}
}
else {
// CLICK / TAP (if the above didn't cancel)
if(didDoubleTap() && ret!==false) {
//Trigger the tap events...
ret = triggerHandlerForGesture(event, phase, DOUBLE_TAP);
}
// CLICK / TAP (if the above didn't cancel)
else if(didLongTap() && ret!==false) {
//Trigger the tap events...
ret = triggerHandlerForGesture(event, phase, LONG_TAP);
}
// CLICK / TAP (if the above didn't cancel)
else if(didTap() && ret!==false) {
//Trigger the tap event..
ret = triggerHandlerForGesture(event, phase, TAP);
}
}
// If we are cancelling the gesture, then manually trigger the reset handler
if (phase === PHASE_CANCEL) {
if(hasSwipes() ) {
ret = triggerHandlerForGesture(event, phase, SWIPE);
}
if(hasPinches()) {
ret = triggerHandlerForGesture(event, phase, PINCH);
}
touchCancel(event);
}
// If we are ending the gesture, then manually trigger the reset handler IF all fingers are off
if(phase === PHASE_END) {
//If we support touch, then check that all fingers are off before we cancel
if (touches) {
if(!touches.length) {
touchCancel(event);
}
}
else {
touchCancel(event);
}
}
return ret;
}
/**
* Trigger the relevant event handler
* The handlers are passed the original event, the element that was swiped, and in the case of the catch all handler, the direction that was swiped, "left", "right", "up", or "down"
* @param {object} event the original event object
* @param {string} phase the phase of the swipe (start, end cancel etc) {@link $.fn.swipe.phases}
* @param {string} gesture the gesture to trigger a handler for : PINCH or SWIPE {@link $.fn.swipe.gestures}
* @return Boolean False, to indicate that the event should stop propagation, or void.
* @inner
*/
function triggerHandlerForGesture(event, phase, gesture) {
var ret;
//SWIPES....
if(gesture==SWIPE) {
//Trigger status every time..
//Trigger the event...
$element.trigger('swipeStatus', [phase, direction || null, distance || 0, duration || 0, fingerCount, fingerData]);
//Fire the callback
if (options.swipeStatus) {
ret = options.swipeStatus.call($element, event, phase, direction || null, distance || 0, duration || 0, fingerCount, fingerData);
//If the status cancels, then dont run the subsequent event handlers..
if(ret===false) return false;
}
if (phase == PHASE_END && validateSwipe()) {
//Fire the catch all event
$element.trigger('swipe', [direction, distance, duration, fingerCount, fingerData]);
//Fire catch all callback
if (options.swipe) {
ret = options.swipe.call($element, event, direction, distance, duration, fingerCount, fingerData);
//If the status cancels, then dont run the subsequent event handlers..
if(ret===false) return false;
}
//trigger direction specific event handlers
switch (direction) {
case LEFT:
//Trigger the event
$element.trigger('swipeLeft', [direction, distance, duration, fingerCount, fingerData]);
//Fire the callback
if (options.swipeLeft) {
ret = options.swipeLeft.call($element, event, direction, distance, duration, fingerCount, fingerData);
}
break;
case RIGHT:
//Trigger the event
$element.trigger('swipeRight', [direction, distance, duration, fingerCount, fingerData]);
//Fire the callback
if (options.swipeRight) {
ret = options.swipeRight.call($element, event, direction, distance, duration, fingerCount, fingerData);
}
break;
case UP:
//Trigger the event
$element.trigger('swipeUp', [direction, distance, duration, fingerCount, fingerData]);
//Fire the callback
if (options.swipeUp) {
ret = options.swipeUp.call($element, event, direction, distance, duration, fingerCount, fingerData);
}
break;
case DOWN:
//Trigger the event
$element.trigger('swipeDown', [direction, distance, duration, fingerCount, fingerData]);
//Fire the callback
if (options.swipeDown) {
ret = options.swipeDown.call($element, event, direction, distance, duration, fingerCount, fingerData);
}
break;
}
}
}
//PINCHES....
if(gesture==PINCH) {
//Trigger the event
$element.trigger('pinchStatus', [phase, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData]);
//Fire the callback
if (options.pinchStatus) {
ret = options.pinchStatus.call($element, event, phase, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData);
//If the status cancels, then dont run the subsequent event handlers..
if(ret===false) return false;
}
if(phase==PHASE_END && validatePinch()) {
switch (pinchDirection) {
case IN:
//Trigger the event
$element.trigger('pinchIn', [pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData]);
//Fire the callback
if (options.pinchIn) {
ret = options.pinchIn.call($element, event, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData);
}
break;
case OUT:
//Trigger the event
$element.trigger('pinchOut', [pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData]);
//Fire the callback
if (options.pinchOut) {
ret = options.pinchOut.call($element, event, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData);
}
break;
}
}
}
if(gesture==TAP) {
if(phase === PHASE_CANCEL || phase === PHASE_END) {
//Cancel any existing double tap
clearTimeout(singleTapTimeout);
//Cancel hold timeout
clearTimeout(holdTimeout);
//If we are also looking for doubelTaps, wait incase this is one...
if(hasDoubleTap() && !inDoubleTap()) {
//Cache the time of this tap
doubleTapStartTime = getTimeStamp();
//Now wait for the double tap timeout, and trigger this single tap
//if its not cancelled by a double tap
singleTapTimeout = setTimeout($.proxy(function() {
doubleTapStartTime=null;
//Trigger the event
$element.trigger('tap', [event.target]);
//Fire the callback
if(options.tap) {
ret = options.tap.call($element, event, event.target);
}
}, this), options.doubleTapThreshold );
} else {
doubleTapStartTime=null;
//Trigger the event
$element.trigger('tap', [event.target]);
//Fire the callback
if(options.tap) {
ret = options.tap.call($element, event, event.target);
}
}
}
}
else if (gesture==DOUBLE_TAP) {
if(phase === PHASE_CANCEL || phase === PHASE_END) {
//Cancel any pending singletap
clearTimeout(singleTapTimeout);
doubleTapStartTime=null;
//Trigger the event
$element.trigger('doubletap', [event.target]);
//Fire the callback
if(options.doubleTap) {
ret = options.doubleTap.call($element, event, event.target);
}
}
}
else if (gesture==LONG_TAP) {
if(phase === PHASE_CANCEL || phase === PHASE_END) {
//Cancel any pending singletap (shouldnt be one)
clearTimeout(singleTapTimeout);
doubleTapStartTime=null;
//Trigger the event
$element.trigger('longtap', [event.target]);
//Fire the callback
if(options.longTap) {
ret = options.longTap.call($element, event, event.target);
}
}
}
return ret;
}
//
// GESTURE VALIDATION
//
/**
* Checks the user has swipe far enough
* @return Boolean if threshold
has been set, return true if the threshold was met, else false.
* If no threshold was set, then we return true.
* @inner
*/
function validateSwipeDistance() {
var valid = true;
//If we made it past the min swipe distance..
if (options.threshold !== null) {
valid = distance >= options.threshold;
}
return valid;
}
/**
* Checks the user has swiped back to cancel.
* @return Boolean if cancelThreshold
has been set, return true if the cancelThreshold was met, else false.
* If no cancelThreshold was set, then we return true.
* @inner
*/
function didSwipeBackToCancel() {
var cancelled = false;
if(options.cancelThreshold !== null && direction !==null) {
cancelled = (getMaxDistance( direction ) - distance) >= options.cancelThreshold;
}
return cancelled;
}
/**
* Checks the user has pinched far enough
* @return Boolean if pinchThreshold
has been set, return true if the threshold was met, else false.
* If no threshold was set, then we return true.
* @inner
*/
function validatePinchDistance() {
if (options.pinchThreshold !== null) {
return pinchDistance >= options.pinchThreshold;
}
return true;
}
/**
* Checks that the time taken to swipe meets the minimum / maximum requirements
* @return Boolean
* @inner
*/
function validateSwipeTime() {
var result;
//If no time set, then return true
if (options.maxTimeThreshold) {
if (duration >= options.maxTimeThreshold) {
result = false;
} else {
result = true;
}
}
else {
result = true;
}
return result;
}
/**
* Checks direction of the swipe and the value allowPageScroll to see if we should allow or prevent the default behaviour from occurring.
* This will essentially allow page scrolling or not when the user is swiping on a touchSwipe object.
* @param {object} jqEvent The normalised jQuery representation of the event object.
* @param {string} direction The direction of the event. See {@link $.fn.swipe.directions}
* @see $.fn.swipe.directions
* @inner
*/
function validateDefaultEvent(jqEvent, direction) {
//If we have no pinches, then do this
//If we have a pinch, and we we have 2 fingers or more down, then dont allow page scroll.
//If the option is set, allways allow the event to bubble up (let user handle wiredness)
if( options.preventDefaultEvents === false) {
return;
}
if (options.allowPageScroll === NONE) {
jqEvent.preventDefault();
} else {
var auto = options.allowPageScroll === AUTO;
switch (direction) {
case LEFT:
if ((options.swipeLeft && auto) || (!auto && options.allowPageScroll != HORIZONTAL)) {
jqEvent.preventDefault();
}
break;
case RIGHT:
if ((options.swipeRight && auto) || (!auto && options.allowPageScroll != HORIZONTAL)) {
jqEvent.preventDefault();
}
break;
case UP:
if ((options.swipeUp && auto) || (!auto && options.allowPageScroll != VERTICAL)) {
jqEvent.preventDefault();
}
break;
case DOWN:
if ((options.swipeDown && auto) || (!auto && options.allowPageScroll != VERTICAL)) {
jqEvent.preventDefault();
}
break;
}
}
}
// PINCHES
/**
* Returns true of the current pinch meets the thresholds
* @return Boolean
* @inner
*/
function validatePinch() {
var hasCorrectFingerCount = validateFingers();
var hasEndPoint = validateEndPoint();
var hasCorrectDistance = validatePinchDistance();
return hasCorrectFingerCount && hasEndPoint && hasCorrectDistance;
}
/**
* Returns true if any Pinch events have been registered
* @return Boolean
* @inner
*/
function hasPinches() {
//Enure we dont return 0 or null for false values
return !!(options.pinchStatus || options.pinchIn || options.pinchOut);
}
/**
* Returns true if we are detecting pinches, and have one
* @return Boolean
* @inner
*/
function didPinch() {
//Enure we dont return 0 or null for false values
return !!(validatePinch() && hasPinches());
}
// SWIPES
/**
* Returns true if the current swipe meets the thresholds
* @return Boolean
* @inner
*/
function validateSwipe() {
//Check validity of swipe
var hasValidTime = validateSwipeTime();
var hasValidDistance = validateSwipeDistance();
var hasCorrectFingerCount = validateFingers();
var hasEndPoint = validateEndPoint();
var didCancel = didSwipeBackToCancel();
// if the user swiped more than the minimum length, perform the appropriate action
// hasValidDistance is null when no distance is set
var valid = !didCancel && hasEndPoint && hasCorrectFingerCount && hasValidDistance && hasValidTime;
return valid;
}
/**
* Returns true if any Swipe events have been registered
* @return Boolean
* @inner
*/
function hasSwipes() {
//Enure we dont return 0 or null for false values
return !!(options.swipe || options.swipeStatus || options.swipeLeft || options.swipeRight || options.swipeUp || options.swipeDown);
}
/**
* Returns true if we are detecting swipes and have one
* @return Boolean
* @inner
*/
function didSwipe() {
//Enure we dont return 0 or null for false values
return !!(validateSwipe() && hasSwipes());
}
/**
* Returns true if we have matched the number of fingers we are looking for
* @return Boolean
* @inner
*/
function validateFingers() {
//The number of fingers we want were matched, or on desktop we ignore
return ((fingerCount === options.fingers || options.fingers === ALL_FINGERS) || !SUPPORTS_TOUCH);
}
/**
* Returns true if we have an end point for the swipe
* @return Boolean
* @inner
*/
function validateEndPoint() {
//We have an end value for the finger
return fingerData[0].end.x !== 0;
}
// TAP / CLICK
/**
* Returns true if a click / tap events have been registered
* @return Boolean
* @inner
*/
function hasTap() {
//Enure we dont return 0 or null for false values
return !!(options.tap) ;
}
/**
* Returns true if a double tap events have been registered
* @return Boolean
* @inner
*/
function hasDoubleTap() {
//Enure we dont return 0 or null for false values
return !!(options.doubleTap) ;
}
/**
* Returns true if any long tap events have been registered
* @return Boolean
* @inner
*/
function hasLongTap() {
//Enure we dont return 0 or null for false values
return !!(options.longTap) ;
}
/**
* Returns true if we could be in the process of a double tap (one tap has occurred, we are listening for double taps, and the threshold hasn't past.
* @return Boolean
* @inner
*/
function validateDoubleTap() {
if(doubleTapStartTime==null){
return false;
}
var now = getTimeStamp();
return (hasDoubleTap() && ((now-doubleTapStartTime) <= options.doubleTapThreshold));
}
/**
* Returns true if we could be in the process of a double tap (one tap has occurred, we are listening for double taps, and the threshold hasn't past.
* @return Boolean
* @inner
*/
function inDoubleTap() {
return validateDoubleTap();
}
/**
* Returns true if we have a valid tap
* @return Boolean
* @inner
*/
function validateTap() {
return ((fingerCount === 1 || !SUPPORTS_TOUCH) && (isNaN(distance) || distance < options.threshold));
}
/**
* Returns true if we have a valid long tap
* @return Boolean
* @inner
*/
function validateLongTap() {
//slight threshold on moving finger
return ((duration > options.longTapThreshold) && (distance < DOUBLE_TAP_THRESHOLD));
}
/**
* Returns true if we are detecting taps and have one
* @return Boolean
* @inner
*/
function didTap() {
//Enure we dont return 0 or null for false values
return !!(validateTap() && hasTap());
}
/**
* Returns true if we are detecting double taps and have one
* @return Boolean
* @inner
*/
function didDoubleTap() {
//Enure we dont return 0 or null for false values
return !!(validateDoubleTap() && hasDoubleTap());
}
/**
* Returns true if we are detecting long taps and have one
* @return Boolean
* @inner
*/
function didLongTap() {
//Enure we dont return 0 or null for false values
return !!(validateLongTap() && hasLongTap());
}
// MULTI FINGER TOUCH
/**
* Starts tracking the time between 2 finger releases, and keeps track of how many fingers we initially had up
* @inner
*/
function startMultiFingerRelease() {
previousTouchEndTime = getTimeStamp();
fingerCountAtRelease = event.touches.length+1;
}
/**
* Cancels the tracking of time between 2 finger releases, and resets counters
* @inner
*/
function cancelMultiFingerRelease() {
previousTouchEndTime = 0;
fingerCountAtRelease = 0;
}
/**
* Checks if we are in the threshold between 2 fingers being released
* @return Boolean
* @inner
*/
function inMultiFingerRelease() {
var withinThreshold = false;
if(previousTouchEndTime) {
var diff = getTimeStamp() - previousTouchEndTime
if( diff<=options.fingerReleaseThreshold ) {
withinThreshold = true;
}
}
return withinThreshold;
}
/**
* gets a data flag to indicate that a touch is in progress
* @return Boolean
* @inner
*/
function getTouchInProgress() {
//strict equality to ensure only true and false are returned
return !!($element.data(PLUGIN_NS+'_intouch') === true);
}
/**
* Sets a data flag to indicate that a touch is in progress
* @param {boolean} val The value to set the property to
* @inner
*/
function setTouchInProgress(val) {
//Add or remove event listeners depending on touch status
if(val===true) {
$element.bind(MOVE_EV, touchMove);
$element.bind(END_EV, touchEnd);
//we only have leave events on desktop, we manually calcuate leave on touch as its not supported in webkit
if(LEAVE_EV) {
$element.bind(LEAVE_EV, touchLeave);
}
} else {
$element.unbind(MOVE_EV, touchMove, false);
$element.unbind(END_EV, touchEnd, false);
//we only have leave events on desktop, we manually calcuate leave on touch as its not supported in webkit
if(LEAVE_EV) {
$element.unbind(LEAVE_EV, touchLeave, false);
}
}
//strict equality to ensure only true and false can update the value
$element.data(PLUGIN_NS+'_intouch', val === true);
}
/**
* Creates the finger data for the touch/finger in the event object.
* @param {int} id The id to store the finger data under (usually the order the fingers were pressed)
* @param {object} evt The event object containing finger data
* @return finger data object
* @inner
*/
function createFingerData(id, evt) {
var f = {
start:{ x: 0, y: 0 },
end:{ x: 0, y: 0 }
};
f.start.x = f.end.x = evt.pageX||evt.clientX;
f.start.y = f.end.y = evt.pageY||evt.clientY;
fingerData[id] = f;
return f;
}
/**
* Updates the finger data for a particular event object
* @param {object} evt The event object containing the touch/finger data to upadte
* @return a finger data object.
* @inner
*/
function updateFingerData(evt) {
var id = evt.identifier!==undefined ? evt.identifier : 0;
var f = getFingerData( id );
if (f === null) {
f = createFingerData(id, evt);
}
f.end.x = evt.pageX||evt.clientX;
f.end.y = evt.pageY||evt.clientY;
return f;
}
/**
* Returns a finger data object by its event ID.
* Each touch event has an identifier property, which is used
* to track repeat touches
* @param {int} id The unique id of the finger in the sequence of touch events.
* @return a finger data object.
* @inner
*/
function getFingerData(id) {
return fingerData[id] || null;
}
/**
* Sets the maximum distance swiped in the given direction.
* If the new value is lower than the current value, the max value is not changed.
* @param {string} direction The direction of the swipe
* @param {int} distance The distance of the swipe
* @inner
*/
function setMaxDistance(direction, distance) {
distance = Math.max(distance, getMaxDistance(direction) );
maximumsMap[direction].distance = distance;
}
/**
* gets the maximum distance swiped in the given direction.
* @param {string} direction The direction of the swipe
* @return int The distance of the swipe
* @inner
*/
function getMaxDistance(direction) {
if (maximumsMap[direction]) return maximumsMap[direction].distance;
return undefined;
}
/**
* Creats a map of directions to maximum swiped values.
* @return Object A dictionary of maximum values, indexed by direction.
* @inner
*/
function createMaximumsData() {
var maxData={};
maxData[LEFT]=createMaximumVO(LEFT);
maxData[RIGHT]=createMaximumVO(RIGHT);
maxData[UP]=createMaximumVO(UP);
maxData[DOWN]=createMaximumVO(DOWN);
return maxData;
}
/**
* Creates a map maximum swiped values for a given swipe direction
* @param {string} The direction that these values will be associated with
* @return Object Maximum values
* @inner
*/
function createMaximumVO(dir) {
return {
direction:dir,
distance:0
}
}
//
// MATHS / UTILS
//
/**
* Calculate the duration of the swipe
* @return int
* @inner
*/
function calculateDuration() {
return endTime - startTime;
}
/**
* Calculate the distance between 2 touches (pinch)
* @param {point} startPoint A point object containing x and y co-ordinates
* @param {point} endPoint A point object containing x and y co-ordinates
* @return int;
* @inner
*/
function calculateTouchesDistance(startPoint, endPoint) {
var diffX = Math.abs(startPoint.x - endPoint.x);
var diffY = Math.abs(startPoint.y - endPoint.y);
return Math.round(Math.sqrt(diffX*diffX+diffY*diffY));
}
/**
* Calculate the zoom factor between the start and end distances
* @param {int} startDistance Distance (between 2 fingers) the user started pinching at
* @param {int} endDistance Distance (between 2 fingers) the user ended pinching at
* @return float The zoom value from 0 to 1.
* @inner
*/
function calculatePinchZoom(startDistance, endDistance) {
var percent = (endDistance/startDistance) * 1;
return percent.toFixed(2);
}
/**
* Returns the pinch direction, either IN or OUT for the given points
* @return string Either {@link $.fn.swipe.directions.IN} or {@link $.fn.swipe.directions.OUT}
* @see $.fn.swipe.directions
* @inner
*/
function calculatePinchDirection() {
if(pinchZoom<1) {
return OUT;
}
else {
return IN;
}
}
/**
* Calculate the length / distance of the swipe
* @param {point} startPoint A point object containing x and y co-ordinates
* @param {point} endPoint A point object containing x and y co-ordinates
* @return int
* @inner
*/
function calculateDistance(startPoint, endPoint) {
return Math.round(Math.sqrt(Math.pow(endPoint.x - startPoint.x, 2) + Math.pow(endPoint.y - startPoint.y, 2)));
}
/**
* Calculate the angle of the swipe
* @param {point} startPoint A point object containing x and y co-ordinates
* @param {point} endPoint A point object containing x and y co-ordinates
* @return int
* @inner
*/
function calculateAngle(startPoint, endPoint) {
var x = startPoint.x - endPoint.x;
var y = endPoint.y - startPoint.y;
var r = Math.atan2(y, x); //radians
var angle = Math.round(r * 180 / Math.PI); //degrees
//ensure value is positive
if (angle < 0) {
angle = 360 - Math.abs(angle);
}
return angle;
}
/**
* Calculate the direction of the swipe
* This will also call calculateAngle to get the latest angle of swipe
* @param {point} startPoint A point object containing x and y co-ordinates
* @param {point} endPoint A point object containing x and y co-ordinates
* @return string Either {@link $.fn.swipe.directions.LEFT} / {@link $.fn.swipe.directions.RIGHT} / {@link $.fn.swipe.directions.DOWN} / {@link $.fn.swipe.directions.UP}
* @see $.fn.swipe.directions
* @inner
*/
function calculateDirection(startPoint, endPoint ) {
var angle = calculateAngle(startPoint, endPoint);
if ((angle <= 45) && (angle >= 0)) {
return LEFT;
} else if ((angle <= 360) && (angle >= 315)) {
return LEFT;
} else if ((angle >= 135) && (angle <= 225)) {
return RIGHT;
} else if ((angle > 45) && (angle < 135)) {
return DOWN;
} else {
return UP;
}
}
/**
* Returns a MS time stamp of the current time
* @return int
* @inner
*/
function getTimeStamp() {
var now = new Date();
return now.getTime();
}
/**
* Returns a bounds object with left, right, top and bottom properties for the element specified.
* @param {DomNode} The DOM node to get the bounds for.
*/
function getbounds( el ) {
el = $(el);
var offset = el.offset();
var bounds = {
left:offset.left,
right:offset.left+el.outerWidth(),
top:offset.top,
bottom:offset.top+el.outerHeight()
}
return bounds;
}
/**
* Checks if the point object is in the bounds object.
* @param {object} point A point object.
* @param {int} point.x The x value of the point.
* @param {int} point.y The x value of the point.
* @param {object} bounds The bounds object to test
* @param {int} bounds.left The leftmost value
* @param {int} bounds.right The righttmost value
* @param {int} bounds.top The topmost value
* @param {int} bounds.bottom The bottommost value
*/
function isInBounds(point, bounds) {
return (point.x > bounds.left && point.x < bounds.right && point.y > bounds.top && point.y < bounds.bottom);
};
}
/**
* A catch all handler that is triggered for all swipe directions.
* @name $.fn.swipe#swipe
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler that is triggered for "left" swipes.
* @name $.fn.swipe#swipeLeft
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler that is triggered for "right" swipes.
* @name $.fn.swipe#swipeRight
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler that is triggered for "up" swipes.
* @name $.fn.swipe#swipeUp
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler that is triggered for "down" swipes.
* @name $.fn.swipe#swipeDown
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler triggered for every phase of the swipe. This handler is constantly fired for the duration of the pinch.
* This is triggered regardless of swipe thresholds.
* @name $.fn.swipe#swipeStatus
* @event
* @default null
* @param {EventObject} event The original event object
* @param {string} phase The phase of the swipe event. See {@link $.fn.swipe.phases}
* @param {string} direction The direction the user swiped in. This is null if the user has yet to move. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user swiped. This is 0 if the user has yet to move.
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler triggered for pinch in events.
* @name $.fn.swipe#pinchIn
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user pinched
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {int} zoom The zoom/scale level the user pinched too, 0-1.
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler triggered for pinch out events.
* @name $.fn.swipe#pinchOut
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user pinched
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {int} zoom The zoom/scale level the user pinched too, 0-1.
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A handler triggered for all pinch events. This handler is constantly fired for the duration of the pinch. This is triggered regardless of thresholds.
* @name $.fn.swipe#pinchStatus
* @event
* @default null
* @param {EventObject} event The original event object
* @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions}
* @param {int} distance The distance the user pinched
* @param {int} duration The duration of the swipe in milliseconds
* @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
* @param {int} zoom The zoom/scale level the user pinched too, 0-1.
* @param {object} fingerData The coordinates of fingers in event
*/
/**
* A click handler triggered when a user simply clicks, rather than swipes on an element.
* This is deprecated since version 1.6.2, any assignment to click will be assigned to the tap handler.
* You cannot use on
to bind to this event as the default jQ click
event will be triggered.
* Use the tap
event instead.
* @name $.fn.swipe#click
* @event
* @deprecated since version 1.6.2, please use {@link $.fn.swipe#tap} instead
* @default null
* @param {EventObject} event The original event object
* @param {DomObject} target The element clicked on.
*/
/**
* A click / tap handler triggered when a user simply clicks or taps, rather than swipes on an element.
* @name $.fn.swipe#tap
* @event
* @default null
* @param {EventObject} event The original event object
* @param {DomObject} target The element clicked on.
*/
/**
* A double tap handler triggered when a user double clicks or taps on an element.
* You can set the time delay for a double tap with the {@link $.fn.swipe.defaults#doubleTapThreshold} property.
* Note: If you set both doubleTap
and tap
handlers, the tap
event will be delayed by the doubleTapThreshold
* as the script needs to check if its a double tap.
* @name $.fn.swipe#doubleTap
* @see $.fn.swipe.defaults#doubleTapThreshold
* @event
* @default null
* @param {EventObject} event The original event object
* @param {DomObject} target The element clicked on.
*/
/**
* A long tap handler triggered once a tap has been release if the tap was longer than the longTapThreshold.
* You can set the time delay for a long tap with the {@link $.fn.swipe.defaults#longTapThreshold} property.
* @name $.fn.swipe#longTap
* @see $.fn.swipe.defaults#longTapThreshold
* @event
* @default null
* @param {EventObject} event The original event object
* @param {DomObject} target The element clicked on.
*/
/**
* A hold tap handler triggered as soon as the longTapThreshold is reached
* You can set the time delay for a long tap with the {@link $.fn.swipe.defaults#longTapThreshold} property.
* @name $.fn.swipe#hold
* @see $.fn.swipe.defaults#longTapThreshold
* @event
* @default null
* @param {EventObject} event The original event object
* @param {DomObject} target The element clicked on.
*/
}));
// THEMEPUNCH INTERNAL HANDLINGS
if(typeof(console) === 'undefined') {
var console = {};
console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = console.groupCollapsed = function() {};
}
// THEMEPUNCH LOGS
if (window.tplogs==true)
try {
console.groupCollapsed("ThemePunch GreenSocks Logs");
} catch(e) { }
// SANDBOX GREENSOCK
var oldgs = window.GreenSockGlobals,
oldgs_queue = window._gsQueue;
var punchgs = window.GreenSockGlobals = {};
if (window.tplogs==true)
try {
console.info("Build GreenSock SandBox for ThemePunch Plugins");
console.info("GreenSock TweenLite Engine Initalised by ThemePunch Plugin");
} catch(e) {}
/*!
* VERSION: 1.15.5
* DATE: 2016-07-08
* UPDATES AND DOCS AT: http://greensock.com
*
* @license Copyright (c) 2008-2016, GreenSock. All rights reserved.
* This work is subject to the terms at http://greensock.com/standard-license or for
* Club GreenSock members, the software agreement that was issued with your membership.
*
* @author: Jack Doyle, jack@greensock.com
**/
var _gsScope = (typeof(module) !== "undefined" && module.exports && typeof(global) !== "undefined") ? global : this || window; //helps ensure compatibility with AMD/RequireJS and CommonJS/Node
(_gsScope._gsQueue || (_gsScope._gsQueue = [])).push( function() {
"use strict";
_gsScope._gsDefine("easing.Back", ["easing.Ease"], function(Ease) {
var w = (_gsScope.GreenSockGlobals || _gsScope),
gs = w.com.greensock,
_2PI = Math.PI * 2,
_HALF_PI = Math.PI / 2,
_class = gs._class,
_create = function(n, f) {
var C = _class("easing." + n, function(){}, true),
p = C.prototype = new Ease();
p.constructor = C;
p.getRatio = f;
return C;
},
_easeReg = Ease.register || function(){}, //put an empty function in place just as a safety measure in case someone loads an OLD version of TweenLite.js where Ease.register doesn't exist.
_wrap = function(name, EaseOut, EaseIn, EaseInOut, aliases) {
var C = _class("easing."+name, {
easeOut:new EaseOut(),
easeIn:new EaseIn(),
easeInOut:new EaseInOut()
}, true);
_easeReg(C, name);
return C;
},
EasePoint = function(time, value, next) {
this.t = time;
this.v = value;
if (next) {
this.next = next;
next.prev = this;
this.c = next.v - value;
this.gap = next.t - time;
}
},
//Back
_createBack = function(n, f) {
var C = _class("easing." + n, function(overshoot) {
this._p1 = (overshoot || overshoot === 0) ? overshoot : 1.70158;
this._p2 = this._p1 * 1.525;
}, true),
p = C.prototype = new Ease();
p.constructor = C;
p.getRatio = f;
p.config = function(overshoot) {
return new C(overshoot);
};
return C;
},
Back = _wrap("Back",
_createBack("BackOut", function(p) {
return ((p = p - 1) * p * ((this._p1 + 1) * p + this._p1) + 1);
}),
_createBack("BackIn", function(p) {
return p * p * ((this._p1 + 1) * p - this._p1);
}),
_createBack("BackInOut", function(p) {
return ((p *= 2) < 1) ? 0.5 * p * p * ((this._p2 + 1) * p - this._p2) : 0.5 * ((p -= 2) * p * ((this._p2 + 1) * p + this._p2) + 2);
})
),
//SlowMo
SlowMo = _class("easing.SlowMo", function(linearRatio, power, yoyoMode) {
power = (power || power === 0) ? power : 0.7;
if (linearRatio == null) {
linearRatio = 0.7;
} else if (linearRatio > 1) {
linearRatio = 1;
}
this._p = (linearRatio !== 1) ? power : 0;
this._p1 = (1 - linearRatio) / 2;
this._p2 = linearRatio;
this._p3 = this._p1 + this._p2;
this._calcEnd = (yoyoMode === true);
}, true),
p = SlowMo.prototype = new Ease(),
SteppedEase, RoughEase, _createElastic;
p.constructor = SlowMo;
p.getRatio = function(p) {
var r = p + (0.5 - p) * this._p;
if (p < this._p1) {
return this._calcEnd ? 1 - ((p = 1 - (p / this._p1)) * p) : r - ((p = 1 - (p / this._p1)) * p * p * p * r);
} else if (p > this._p3) {
return this._calcEnd ? 1 - (p = (p - this._p3) / this._p1) * p : r + ((p - r) * (p = (p - this._p3) / this._p1) * p * p * p);
}
return this._calcEnd ? 1 : r;
};
SlowMo.ease = new SlowMo(0.7, 0.7);
p.config = SlowMo.config = function(linearRatio, power, yoyoMode) {
return new SlowMo(linearRatio, power, yoyoMode);
};
//SteppedEase
SteppedEase = _class("easing.SteppedEase", function(steps) {
steps = steps || 1;
this._p1 = 1 / steps;
this._p2 = steps + 1;
}, true);
p = SteppedEase.prototype = new Ease();
p.constructor = SteppedEase;
p.getRatio = function(p) {
if (p < 0) {
p = 0;
} else if (p >= 1) {
p = 0.999999999;
}
return ((this._p2 * p) >> 0) * this._p1;
};
p.config = SteppedEase.config = function(steps) {
return new SteppedEase(steps);
};
//RoughEase
RoughEase = _class("easing.RoughEase", function(vars) {
vars = vars || {};
var taper = vars.taper || "none",
a = [],
cnt = 0,
points = (vars.points || 20) | 0,
i = points,
randomize = (vars.randomize !== false),
clamp = (vars.clamp === true),
template = (vars.template instanceof Ease) ? vars.template : null,
strength = (typeof(vars.strength) === "number") ? vars.strength * 0.4 : 0.4,
x, y, bump, invX, obj, pnt;
while (--i > -1) {
x = randomize ? Math.random() : (1 / points) * i;
y = template ? template.getRatio(x) : x;
if (taper === "none") {
bump = strength;
} else if (taper === "out") {
invX = 1 - x;
bump = invX * invX * strength;
} else if (taper === "in") {
bump = x * x * strength;
} else if (x < 0.5) { //"both" (start)
invX = x * 2;
bump = invX * invX * 0.5 * strength;
} else { //"both" (end)
invX = (1 - x) * 2;
bump = invX * invX * 0.5 * strength;
}
if (randomize) {
y += (Math.random() * bump) - (bump * 0.5);
} else if (i % 2) {
y += bump * 0.5;
} else {
y -= bump * 0.5;
}
if (clamp) {
if (y > 1) {
y = 1;
} else if (y < 0) {
y = 0;
}
}
a[cnt++] = {x:x, y:y};
}
a.sort(function(a, b) {
return a.x - b.x;
});
pnt = new EasePoint(1, 1, null);
i = points;
while (--i > -1) {
obj = a[i];
pnt = new EasePoint(obj.x, obj.y, pnt);
}
this._prev = new EasePoint(0, 0, (pnt.t !== 0) ? pnt : pnt.next);
}, true);
p = RoughEase.prototype = new Ease();
p.constructor = RoughEase;
p.getRatio = function(p) {
var pnt = this._prev;
if (p > pnt.t) {
while (pnt.next && p >= pnt.t) {
pnt = pnt.next;
}
pnt = pnt.prev;
} else {
while (pnt.prev && p <= pnt.t) {
pnt = pnt.prev;
}
}
this._prev = pnt;
return (pnt.v + ((p - pnt.t) / pnt.gap) * pnt.c);
};
p.config = function(vars) {
return new RoughEase(vars);
};
RoughEase.ease = new RoughEase();
//Bounce
_wrap("Bounce",
_create("BounceOut", function(p) {
if (p < 1 / 2.75) {
return 7.5625 * p * p;
} else if (p < 2 / 2.75) {
return 7.5625 * (p -= 1.5 / 2.75) * p + 0.75;
} else if (p < 2.5 / 2.75) {
return 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375;
}
return 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375;
}),
_create("BounceIn", function(p) {
if ((p = 1 - p) < 1 / 2.75) {
return 1 - (7.5625 * p * p);
} else if (p < 2 / 2.75) {
return 1 - (7.5625 * (p -= 1.5 / 2.75) * p + 0.75);
} else if (p < 2.5 / 2.75) {
return 1 - (7.5625 * (p -= 2.25 / 2.75) * p + 0.9375);
}
return 1 - (7.5625 * (p -= 2.625 / 2.75) * p + 0.984375);
}),
_create("BounceInOut", function(p) {
var invert = (p < 0.5);
if (invert) {
p = 1 - (p * 2);
} else {
p = (p * 2) - 1;
}
if (p < 1 / 2.75) {
p = 7.5625 * p * p;
} else if (p < 2 / 2.75) {
p = 7.5625 * (p -= 1.5 / 2.75) * p + 0.75;
} else if (p < 2.5 / 2.75) {
p = 7.5625 * (p -= 2.25 / 2.75) * p + 0.9375;
} else {
p = 7.5625 * (p -= 2.625 / 2.75) * p + 0.984375;
}
return invert ? (1 - p) * 0.5 : p * 0.5 + 0.5;
})
);
//CIRC
_wrap("Circ",
_create("CircOut", function(p) {
return Math.sqrt(1 - (p = p - 1) * p);
}),
_create("CircIn", function(p) {
return -(Math.sqrt(1 - (p * p)) - 1);
}),
_create("CircInOut", function(p) {
return ((p*=2) < 1) ? -0.5 * (Math.sqrt(1 - p * p) - 1) : 0.5 * (Math.sqrt(1 - (p -= 2) * p) + 1);
})
);
//Elastic
_createElastic = function(n, f, def) {
var C = _class("easing." + n, function(amplitude, period) {
this._p1 = (amplitude >= 1) ? amplitude : 1; //note: if amplitude is < 1, we simply adjust the period for a more natural feel. Otherwise the math doesn't work right and the curve starts at 1.
this._p2 = (period || def) / (amplitude < 1 ? amplitude : 1);
this._p3 = this._p2 / _2PI * (Math.asin(1 / this._p1) || 0);
this._p2 = _2PI / this._p2; //precalculate to optimize
}, true),
p = C.prototype = new Ease();
p.constructor = C;
p.getRatio = f;
p.config = function(amplitude, period) {
return new C(amplitude, period);
};
return C;
};
_wrap("Elastic",
_createElastic("ElasticOut", function(p) {
return this._p1 * Math.pow(2, -10 * p) * Math.sin( (p - this._p3) * this._p2 ) + 1;
}, 0.3),
_createElastic("ElasticIn", function(p) {
return -(this._p1 * Math.pow(2, 10 * (p -= 1)) * Math.sin( (p - this._p3) * this._p2 ));
}, 0.3),
_createElastic("ElasticInOut", function(p) {
return ((p *= 2) < 1) ? -0.5 * (this._p1 * Math.pow(2, 10 * (p -= 1)) * Math.sin( (p - this._p3) * this._p2)) : this._p1 * Math.pow(2, -10 *(p -= 1)) * Math.sin( (p - this._p3) * this._p2 ) * 0.5 + 1;
}, 0.45)
);
//Expo
_wrap("Expo",
_create("ExpoOut", function(p) {
return 1 - Math.pow(2, -10 * p);
}),
_create("ExpoIn", function(p) {
return Math.pow(2, 10 * (p - 1)) - 0.001;
}),
_create("ExpoInOut", function(p) {
return ((p *= 2) < 1) ? 0.5 * Math.pow(2, 10 * (p - 1)) : 0.5 * (2 - Math.pow(2, -10 * (p - 1)));
})
);
//Sine
_wrap("Sine",
_create("SineOut", function(p) {
return Math.sin(p * _HALF_PI);
}),
_create("SineIn", function(p) {
return -Math.cos(p * _HALF_PI) + 1;
}),
_create("SineInOut", function(p) {
return -0.5 * (Math.cos(Math.PI * p) - 1);
})
);
_class("easing.EaseLookup", {
find:function(s) {
return Ease.map[s];
}
}, true);
//register the non-standard eases
_easeReg(w.SlowMo, "SlowMo", "ease,");
_easeReg(RoughEase, "RoughEase", "ease,");
_easeReg(SteppedEase, "SteppedEase", "ease,");
return Back;
}, true);
}); if (_gsScope._gsDefine) { _gsScope._gsQueue.pop()(); }
//export to AMD/RequireJS and CommonJS/Node (precursor to full modular build system coming at a later date)
(function() {
"use strict";
var getGlobal = function() {
return (_gsScope.GreenSockGlobals || _gsScope);
};
if (typeof(define) === "function" && define.amd) { //AMD
define(["TweenLite"], getGlobal);
} else if (typeof(module) !== "undefined" && module.exports) { //node
require("../TweenLite.js");
module.exports = getGlobal();
}
}());
/*!
* VERSION: 1.18.6
* DATE: 2016-07-08
* UPDATES AND DOCS AT: http://greensock.com
*
* @license Copyright (c) 2008-2016, GreenSock. All rights reserved.
* This work is subject to the terms at http://greensock.com/standard-license or for
* Club GreenSock members, the software agreement that was issued with your membership.
*
* @author: Jack Doyle, jack@greensock.com
*/
var _gsScope = (typeof(module) !== "undefined" && module.exports && typeof(global) !== "undefined") ? global : this || window; //helps ensure compatibility with AMD/RequireJS and CommonJS/Node
(_gsScope._gsQueue || (_gsScope._gsQueue = [])).push( function() {
"use strict";
_gsScope._gsDefine("TimelineLite", ["core.Animation","core.SimpleTimeline","TweenLite"], function(Animation, SimpleTimeline, TweenLite) {
var TimelineLite = function(vars) {
SimpleTimeline.call(this, vars);
this._labels = {};
this.autoRemoveChildren = (this.vars.autoRemoveChildren === true);
this.smoothChildTiming = (this.vars.smoothChildTiming === true);
this._sortChildren = true;
this._onUpdate = this.vars.onUpdate;
var v = this.vars,
val, p;
for (p in v) {
val = v[p];
if (_isArray(val)) if (val.join("").indexOf("{self}") !== -1) {
v[p] = this._swapSelfInParams(val);
}
}
if (_isArray(v.tweens)) {
this.add(v.tweens, 0, v.align, v.stagger);
}
},
_tinyNum = 0.0000000001,
TweenLiteInternals = TweenLite._internals,
_internals = TimelineLite._internals = {},
_isSelector = TweenLiteInternals.isSelector,
_isArray = TweenLiteInternals.isArray,
_lazyTweens = TweenLiteInternals.lazyTweens,
_lazyRender = TweenLiteInternals.lazyRender,
_globals = _gsScope._gsDefine.globals,
_copy = function(vars) {
var copy = {}, p;
for (p in vars) {
copy[p] = vars[p];
}
return copy;
},
_applyCycle = function(vars, targets, i) {
var alt = vars.cycle,
p, val;
for (p in alt) {
val = alt[p];
vars[p] = (typeof(val) === "function") ? val(i, targets[i]) : val[i % val.length];
}
delete vars.cycle;
},
_pauseCallback = _internals.pauseCallback = function() {},
_slice = function(a) { //don't use [].slice because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
var b = [],
l = a.length,
i;
for (i = 0; i !== l; b.push(a[i++]));
return b;
},
p = TimelineLite.prototype = new SimpleTimeline();
TimelineLite.version = "1.19.0";
p.constructor = TimelineLite;
p.kill()._gc = p._forcingPlayhead = p._hasPause = false;
/* might use later...
//translates a local time inside an animation to the corresponding time on the root/global timeline, factoring in all nesting and timeScales.
function localToGlobal(time, animation) {
while (animation) {
time = (time / animation._timeScale) + animation._startTime;
animation = animation.timeline;
}
return time;
}
//translates the supplied time on the root/global timeline into the corresponding local time inside a particular animation, factoring in all nesting and timeScales
function globalToLocal(time, animation) {
var scale = 1;
time -= localToGlobal(0, animation);
while (animation) {
scale *= animation._timeScale;
animation = animation.timeline;
}
return time * scale;
}
*/
p.to = function(target, duration, vars, position) {
var Engine = (vars.repeat && _globals.TweenMax) || TweenLite;
return duration ? this.add( new Engine(target, duration, vars), position) : this.set(target, vars, position);
};
p.from = function(target, duration, vars, position) {
return this.add( ((vars.repeat && _globals.TweenMax) || TweenLite).from(target, duration, vars), position);
};
p.fromTo = function(target, duration, fromVars, toVars, position) {
var Engine = (toVars.repeat && _globals.TweenMax) || TweenLite;
return duration ? this.add( Engine.fromTo(target, duration, fromVars, toVars), position) : this.set(target, toVars, position);
};
p.staggerTo = function(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
var tl = new TimelineLite({onComplete:onCompleteAll, onCompleteParams:onCompleteAllParams, callbackScope:onCompleteAllScope, smoothChildTiming:this.smoothChildTiming}),
cycle = vars.cycle,
copy, i;
if (typeof(targets) === "string") {
targets = TweenLite.selector(targets) || targets;
}
targets = targets || [];
if (_isSelector(targets)) { //senses if the targets object is a selector. If it is, we should translate it into an array.
targets = _slice(targets);
}
stagger = stagger || 0;
if (stagger < 0) {
targets = _slice(targets);
targets.reverse();
stagger *= -1;
}
for (i = 0; i < targets.length; i++) {
copy = _copy(vars);
if (copy.startAt) {
copy.startAt = _copy(copy.startAt);
if (copy.startAt.cycle) {
_applyCycle(copy.startAt, targets, i);
}
}
if (cycle) {
_applyCycle(copy, targets, i);
if (copy.duration != null) {
duration = copy.duration;
delete copy.duration;
}
}
tl.to(targets[i], duration, copy, i * stagger);
}
return this.add(tl, position);
};
p.staggerFrom = function(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
vars.immediateRender = (vars.immediateRender != false);
vars.runBackwards = true;
return this.staggerTo(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
};
p.staggerFromTo = function(targets, duration, fromVars, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope) {
toVars.startAt = fromVars;
toVars.immediateRender = (toVars.immediateRender != false && fromVars.immediateRender != false);
return this.staggerTo(targets, duration, toVars, stagger, position, onCompleteAll, onCompleteAllParams, onCompleteAllScope);
};
p.call = function(callback, params, scope, position) {
return this.add( TweenLite.delayedCall(0, callback, params, scope), position);
};
p.set = function(target, vars, position) {
position = this._parseTimeOrLabel(position, 0, true);
if (vars.immediateRender == null) {
vars.immediateRender = (position === this._time && !this._paused);
}
return this.add( new TweenLite(target, 0, vars), position);
};
TimelineLite.exportRoot = function(vars, ignoreDelayedCalls) {
vars = vars || {};
if (vars.smoothChildTiming == null) {
vars.smoothChildTiming = true;
}
var tl = new TimelineLite(vars),
root = tl._timeline,
tween, next;
if (ignoreDelayedCalls == null) {
ignoreDelayedCalls = true;
}
root._remove(tl, true);
tl._startTime = 0;
tl._rawPrevTime = tl._time = tl._totalTime = root._time;
tween = root._first;
while (tween) {
next = tween._next;
if (!ignoreDelayedCalls || !(tween instanceof TweenLite && tween.target === tween.vars.onComplete)) {
tl.add(tween, tween._startTime - tween._delay);
}
tween = next;
}
root.add(tl, 0);
return tl;
};
p.add = function(value, position, align, stagger) {
var curTime, l, i, child, tl, beforeRawTime;
if (typeof(position) !== "number") {
position = this._parseTimeOrLabel(position, 0, true, value);
}
if (!(value instanceof Animation)) {
if ((value instanceof Array) || (value && value.push && _isArray(value))) {
align = align || "normal";
stagger = stagger || 0;
curTime = position;
l = value.length;
for (i = 0; i < l; i++) {
if (_isArray(child = value[i])) {
child = new TimelineLite({tweens:child});
}
this.add(child, curTime);
if (typeof(child) !== "string" && typeof(child) !== "function") {
if (align === "sequence") {
curTime = child._startTime + (child.totalDuration() / child._timeScale);
} else if (align === "start") {
child._startTime -= child.delay();
}
}
curTime += stagger;
}
return this._uncache(true);
} else if (typeof(value) === "string") {
return this.addLabel(value, position);
} else if (typeof(value) === "function") {
value = TweenLite.delayedCall(0, value);
} else {
throw("Cannot add " + value + " into the timeline; it is not a tween, timeline, function, or string.");
}
}
SimpleTimeline.prototype.add.call(this, value, position);
//if the timeline has already ended but the inserted tween/timeline extends the duration, we should enable this timeline again so that it renders properly. We should also align the playhead with the parent timeline's when appropriate.
if (this._gc || this._time === this._duration) if (!this._paused) if (this._duration < this.duration()) {
//in case any of the ancestors had completed but should now be enabled...
tl = this;
beforeRawTime = (tl.rawTime() > value._startTime); //if the tween is placed on the timeline so that it starts BEFORE the current rawTime, we should align the playhead (move the timeline). This is because sometimes users will create a timeline, let it finish, and much later append a tween and expect it to run instead of jumping to its end state. While technically one could argue that it should jump to its end state, that's not what users intuitively expect.
while (tl._timeline) {
if (beforeRawTime && tl._timeline.smoothChildTiming) {
tl.totalTime(tl._totalTime, true); //moves the timeline (shifts its startTime) if necessary, and also enables it.
} else if (tl._gc) {
tl._enabled(true, false);
}
tl = tl._timeline;
}
}
return this;
};
p.remove = function(value) {
if (value instanceof Animation) {
this._remove(value, false);
var tl = value._timeline = value.vars.useFrames ? Animation._rootFramesTimeline : Animation._rootTimeline; //now that it's removed, default it to the root timeline so that if it gets played again, it doesn't jump back into this timeline.
value._startTime = (value._paused ? value._pauseTime : tl._time) - ((!value._reversed ? value._totalTime : value.totalDuration() - value._totalTime) / value._timeScale); //ensure that if it gets played again, the timing is correct.
return this;
} else if (value instanceof Array || (value && value.push && _isArray(value))) {
var i = value.length;
while (--i > -1) {
this.remove(value[i]);
}
return this;
} else if (typeof(value) === "string") {
return this.removeLabel(value);
}
return this.kill(null, value);
};
p._remove = function(tween, skipDisable) {
SimpleTimeline.prototype._remove.call(this, tween, skipDisable);
var last = this._last;
if (!last) {
this._time = this._totalTime = this._duration = this._totalDuration = 0;
} else if (this._time > last._startTime + last._totalDuration / last._timeScale) {
this._time = this.duration();
this._totalTime = this._totalDuration;
}
return this;
};
p.append = function(value, offsetOrLabel) {
return this.add(value, this._parseTimeOrLabel(null, offsetOrLabel, true, value));
};
p.insert = p.insertMultiple = function(value, position, align, stagger) {
return this.add(value, position || 0, align, stagger);
};
p.appendMultiple = function(tweens, offsetOrLabel, align, stagger) {
return this.add(tweens, this._parseTimeOrLabel(null, offsetOrLabel, true, tweens), align, stagger);
};
p.addLabel = function(label, position) {
this._labels[label] = this._parseTimeOrLabel(position);
return this;
};
p.addPause = function(position, callback, params, scope) {
var t = TweenLite.delayedCall(0, _pauseCallback, params, scope || this);
t.vars.onComplete = t.vars.onReverseComplete = callback;
t.data = "isPause";
this._hasPause = true;
return this.add(t, position);
};
p.removeLabel = function(label) {
delete this._labels[label];
return this;
};
p.getLabelTime = function(label) {
return (this._labels[label] != null) ? this._labels[label] : -1;
};
p._parseTimeOrLabel = function(timeOrLabel, offsetOrLabel, appendIfAbsent, ignore) {
var i;
//if we're about to add a tween/timeline (or an array of them) that's already a child of this timeline, we should remove it first so that it doesn't contaminate the duration().
if (ignore instanceof Animation && ignore.timeline === this) {
this.remove(ignore);
} else if (ignore && ((ignore instanceof Array) || (ignore.push && _isArray(ignore)))) {
i = ignore.length;
while (--i > -1) {
if (ignore[i] instanceof Animation && ignore[i].timeline === this) {
this.remove(ignore[i]);
}
}
}
if (typeof(offsetOrLabel) === "string") {
return this._parseTimeOrLabel(offsetOrLabel, (appendIfAbsent && typeof(timeOrLabel) === "number" && this._labels[offsetOrLabel] == null) ? timeOrLabel - this.duration() : 0, appendIfAbsent);
}
offsetOrLabel = offsetOrLabel || 0;
if (typeof(timeOrLabel) === "string" && (isNaN(timeOrLabel) || this._labels[timeOrLabel] != null)) { //if the string is a number like "1", check to see if there's a label with that name, otherwise interpret it as a number (absolute value).
i = timeOrLabel.indexOf("=");
if (i === -1) {
if (this._labels[timeOrLabel] == null) {
return appendIfAbsent ? (this._labels[timeOrLabel] = this.duration() + offsetOrLabel) : offsetOrLabel;
}
return this._labels[timeOrLabel] + offsetOrLabel;
}
offsetOrLabel = parseInt(timeOrLabel.charAt(i-1) + "1", 10) * Number(timeOrLabel.substr(i+1));
timeOrLabel = (i > 1) ? this._parseTimeOrLabel(timeOrLabel.substr(0, i-1), 0, appendIfAbsent) : this.duration();
} else if (timeOrLabel == null) {
timeOrLabel = this.duration();
}
return Number(timeOrLabel) + offsetOrLabel;
};
p.seek = function(position, suppressEvents) {
return this.totalTime((typeof(position) === "number") ? position : this._parseTimeOrLabel(position), (suppressEvents !== false));
};
p.stop = function() {
return this.paused(true);
};
p.gotoAndPlay = function(position, suppressEvents) {
return this.play(position, suppressEvents);
};
p.gotoAndStop = function(position, suppressEvents) {
return this.pause(position, suppressEvents);
};
p.render = function(time, suppressEvents, force) {
if (this._gc) {
this._enabled(true, false);
}
var totalDur = (!this._dirty) ? this._totalDuration : this.totalDuration(),
prevTime = this._time,
prevStart = this._startTime,
prevTimeScale = this._timeScale,
prevPaused = this._paused,
tween, isComplete, next, callback, internalForce, pauseTween, curTime;
if (time >= totalDur - 0.0000001) { //to work around occasional floating point math artifacts.
this._totalTime = this._time = totalDur;
if (!this._reversed) if (!this._hasPausedChild()) {
isComplete = true;
callback = "onComplete";
internalForce = !!this._timeline.autoRemoveChildren; //otherwise, if the animation is unpaused/activated after it's already finished, it doesn't get removed from the parent timeline.
if (this._duration === 0) if ((time <= 0 && time >= -0.0000001) || this._rawPrevTime < 0 || this._rawPrevTime === _tinyNum) if (this._rawPrevTime !== time && this._first) {
internalForce = true;
if (this._rawPrevTime > _tinyNum) {
callback = "onReverseComplete";
}
}
}
this._rawPrevTime = (this._duration || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
time = totalDur + 0.0001; //to avoid occasional floating point rounding errors - sometimes child tweens/timelines were not being fully completed (their progress might be 0.999999999999998 instead of 1 because when _time - tween._startTime is performed, floating point errors would return a value that was SLIGHTLY off). Try (999999999999.7 - 999999999999) * 1 = 0.699951171875 instead of 0.7.
} else if (time < 0.0000001) { //to work around occasional floating point math artifacts, round super small values to 0.
this._totalTime = this._time = 0;
if (prevTime !== 0 || (this._duration === 0 && this._rawPrevTime !== _tinyNum && (this._rawPrevTime > 0 || (time < 0 && this._rawPrevTime >= 0)))) {
callback = "onReverseComplete";
isComplete = this._reversed;
}
if (time < 0) {
this._active = false;
if (this._timeline.autoRemoveChildren && this._reversed) { //ensures proper GC if a timeline is resumed after it's finished reversing.
internalForce = isComplete = true;
callback = "onReverseComplete";
} else if (this._rawPrevTime >= 0 && this._first) { //when going back beyond the start, force a render so that zero-duration tweens that sit at the very beginning render their start values properly. Otherwise, if the parent timeline's playhead lands exactly at this timeline's startTime, and then moves backwards, the zero-duration tweens at the beginning would still be at their end state.
internalForce = true;
}
this._rawPrevTime = time;
} else {
this._rawPrevTime = (this._duration || !suppressEvents || time || this._rawPrevTime === time) ? time : _tinyNum; //when the playhead arrives at EXACTLY time 0 (right on top) of a zero-duration timeline or tween, we need to discern if events are suppressed so that when the playhead moves again (next time), it'll trigger the callback. If events are NOT suppressed, obviously the callback would be triggered in this render. Basically, the callback should fire either when the playhead ARRIVES or LEAVES this exact spot, not both. Imagine doing a timeline.seek(0) and there's a callback that sits at 0. Since events are suppressed on that seek() by default, nothing will fire, but when the playhead moves off of that position, the callback should fire. This behavior is what people intuitively expect. We set the _rawPrevTime to be a precise tiny number to indicate this scenario rather than using another property/variable which would increase memory usage. This technique is less readable, but more efficient.
if (time === 0 && isComplete) { //if there's a zero-duration tween at the very beginning of a timeline and the playhead lands EXACTLY at time 0, that tween will correctly render its end values, but we need to keep the timeline alive for one more render so that the beginning values render properly as the parent's playhead keeps moving beyond the begining. Imagine obj.x starts at 0 and then we do tl.set(obj, {x:100}).to(obj, 1, {x:200}) and then later we tl.reverse()...the goal is to have obj.x revert to 0. If the playhead happens to land on exactly 0, without this chunk of code, it'd complete the timeline and remove it from the rendering queue (not good).
tween = this._first;
while (tween && tween._startTime === 0) {
if (!tween._duration) {
isComplete = false;
}
tween = tween._next;
}
}
time = 0; //to avoid occasional floating point rounding errors (could cause problems especially with zero-duration tweens at the very beginning of the timeline)
if (!this._initted) {
internalForce = true;
}
}
} else {
if (this._hasPause && !this._forcingPlayhead && !suppressEvents) {
if (time >= prevTime) {
tween = this._first;
while (tween && tween._startTime <= time && !pauseTween) {
if (!tween._duration) if (tween.data === "isPause" && !tween.ratio && !(tween._startTime === 0 && this._rawPrevTime === 0)) {
pauseTween = tween;
}
tween = tween._next;
}
} else {
tween = this._last;
while (tween && tween._startTime >= time && !pauseTween) {
if (!tween._duration) if (tween.data === "isPause" && tween._rawPrevTime > 0) {
pauseTween = tween;
}
tween = tween._prev;
}
}
if (pauseTween) {
this._time = time = pauseTween._startTime;
this._totalTime = time + (this._cycle * (this._totalDuration + this._repeatDelay));
}
}
this._totalTime = this._time = this._rawPrevTime = time;
}
if ((this._time === prevTime || !this._first) && !force && !internalForce && !pauseTween) {
return;
} else if (!this._initted) {
this._initted = true;
}
if (!this._active) if (!this._paused && this._time !== prevTime && time > 0) {
this._active = true; //so that if the user renders the timeline (as opposed to the parent timeline rendering it), it is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the timeline already finished but the user manually re-renders it as halfway done, for example.
}
if (prevTime === 0) if (this.vars.onStart) if (this._time !== 0 || !this._duration) if (!suppressEvents) {
this._callback("onStart");
}
curTime = this._time;
if (curTime >= prevTime) {
tween = this._first;
while (tween) {
next = tween._next; //record it here because the value could change after rendering...
if (curTime !== this._time || (this._paused && !prevPaused)) { //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
break;
} else if (tween._active || (tween._startTime <= curTime && !tween._paused && !tween._gc)) {
if (pauseTween === tween) {
this.pause();
}
if (!tween._reversed) {
tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
} else {
tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
}
}
tween = next;
}
} else {
tween = this._last;
while (tween) {
next = tween._prev; //record it here because the value could change after rendering...
if (curTime !== this._time || (this._paused && !prevPaused)) { //in case a tween pauses or seeks the timeline when rendering, like inside of an onUpdate/onComplete
break;
} else if (tween._active || (tween._startTime <= prevTime && !tween._paused && !tween._gc)) {
if (pauseTween === tween) {
pauseTween = tween._prev; //the linked list is organized by _startTime, thus it's possible that a tween could start BEFORE the pause and end after it, in which case it would be positioned before the pause tween in the linked list, but we should render it before we pause() the timeline and cease rendering. This is only a concern when going in reverse.
while (pauseTween && pauseTween.endTime() > this._time) {
pauseTween.render( (pauseTween._reversed ? pauseTween.totalDuration() - ((time - pauseTween._startTime) * pauseTween._timeScale) : (time - pauseTween._startTime) * pauseTween._timeScale), suppressEvents, force);
pauseTween = pauseTween._prev;
}
pauseTween = null;
this.pause();
}
if (!tween._reversed) {
tween.render((time - tween._startTime) * tween._timeScale, suppressEvents, force);
} else {
tween.render(((!tween._dirty) ? tween._totalDuration : tween.totalDuration()) - ((time - tween._startTime) * tween._timeScale), suppressEvents, force);
}
}
tween = next;
}
}
if (this._onUpdate) if (!suppressEvents) {
if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onUpdate on a timeline that reports/checks tweened values.
_lazyRender();
}
this._callback("onUpdate");
}
if (callback) if (!this._gc) if (prevStart === this._startTime || prevTimeScale !== this._timeScale) if (this._time === 0 || totalDur >= this.totalDuration()) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline), it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would complete if it was necessary at the new time. The only exception is the timeScale property. Also check _gc because there's a chance that kill() could be called in an onUpdate
if (isComplete) {
if (_lazyTweens.length) { //in case rendering caused any tweens to lazy-init, we should render them because typically when a timeline finishes, users expect things to have rendered fully. Imagine an onComplete on a timeline that reports/checks tweened values.
_lazyRender();
}
if (this._timeline.autoRemoveChildren) {
this._enabled(false, false);
}
this._active = false;
}
if (!suppressEvents && this.vars[callback]) {
this._callback(callback);
}
}
};
p._hasPausedChild = function() {
var tween = this._first;
while (tween) {
if (tween._paused || ((tween instanceof TimelineLite) && tween._hasPausedChild())) {
return true;
}
tween = tween._next;
}
return false;
};
p.getChildren = function(nested, tweens, timelines, ignoreBeforeTime) {
ignoreBeforeTime = ignoreBeforeTime || -9999999999;
var a = [],
tween = this._first,
cnt = 0;
while (tween) {
if (tween._startTime < ignoreBeforeTime) {
//do nothing
} else if (tween instanceof TweenLite) {
if (tweens !== false) {
a[cnt++] = tween;
}
} else {
if (timelines !== false) {
a[cnt++] = tween;
}
if (nested !== false) {
a = a.concat(tween.getChildren(true, tweens, timelines));
cnt = a.length;
}
}
tween = tween._next;
}
return a;
};
p.getTweensOf = function(target, nested) {
var disabled = this._gc,
a = [],
cnt = 0,
tweens, i;
if (disabled) {
this._enabled(true, true); //getTweensOf() filters out disabled tweens, and we have to mark them as _gc = true when the timeline completes in order to allow clean garbage collection, so temporarily re-enable the timeline here.
}
tweens = TweenLite.getTweensOf(target);
i = tweens.length;
while (--i > -1) {
if (tweens[i].timeline === this || (nested && this._contains(tweens[i]))) {
a[cnt++] = tweens[i];
}
}
if (disabled) {
this._enabled(false, true);
}
return a;
};
p.recent = function() {
return this._recent;
};
p._contains = function(tween) {
var tl = tween.timeline;
while (tl) {
if (tl === this) {
return true;
}
tl = tl.timeline;
}
return false;
};
p.shiftChildren = function(amount, adjustLabels, ignoreBeforeTime) {
ignoreBeforeTime = ignoreBeforeTime || 0;
var tween = this._first,
labels = this._labels,
p;
while (tween) {
if (tween._startTime >= ignoreBeforeTime) {
tween._startTime += amount;
}
tween = tween._next;
}
if (adjustLabels) {
for (p in labels) {
if (labels[p] >= ignoreBeforeTime) {
labels[p] += amount;
}
}
}
return this._uncache(true);
};
p._kill = function(vars, target) {
if (!vars && !target) {
return this._enabled(false, false);
}
var tweens = (!target) ? this.getChildren(true, true, false) : this.getTweensOf(target),
i = tweens.length,
changed = false;
while (--i > -1) {
if (tweens[i]._kill(vars, target)) {
changed = true;
}
}
return changed;
};
p.clear = function(labels) {
var tweens = this.getChildren(false, true, true),
i = tweens.length;
this._time = this._totalTime = 0;
while (--i > -1) {
tweens[i]._enabled(false, false);
}
if (labels !== false) {
this._labels = {};
}
return this._uncache(true);
};
p.invalidate = function() {
var tween = this._first;
while (tween) {
tween.invalidate();
tween = tween._next;
}
return Animation.prototype.invalidate.call(this);;
};
p._enabled = function(enabled, ignoreTimeline) {
if (enabled === this._gc) {
var tween = this._first;
while (tween) {
tween._enabled(enabled, true);
tween = tween._next;
}
}
return SimpleTimeline.prototype._enabled.call(this, enabled, ignoreTimeline);
};
p.totalTime = function(time, suppressEvents, uncapped) {
this._forcingPlayhead = true;
var val = Animation.prototype.totalTime.apply(this, arguments);
this._forcingPlayhead = false;
return val;
};
p.duration = function(value) {
if (!arguments.length) {
if (this._dirty) {
this.totalDuration(); //just triggers recalculation
}
return this._duration;
}
if (this.duration() !== 0 && value !== 0) {
this.timeScale(this._duration / value);
}
return this;
};
p.totalDuration = function(value) {
if (!arguments.length) {
if (this._dirty) {
var max = 0,
tween = this._last,
prevStart = 999999999999,
prev, end;
while (tween) {
prev = tween._prev; //record it here in case the tween changes position in the sequence...
if (tween._dirty) {
tween.totalDuration(); //could change the tween._startTime, so make sure the tween's cache is clean before analyzing it.
}
if (tween._startTime > prevStart && this._sortChildren && !tween._paused) { //in case one of the tweens shifted out of order, it needs to be re-inserted into the correct position in the sequence
this.add(tween, tween._startTime - tween._delay);
} else {
prevStart = tween._startTime;
}
if (tween._startTime < 0 && !tween._paused) { //children aren't allowed to have negative startTimes unless smoothChildTiming is true, so adjust here if one is found.
max -= tween._startTime;
if (this._timeline.smoothChildTiming) {
this._startTime += tween._startTime / this._timeScale;
}
this.shiftChildren(-tween._startTime, false, -9999999999);
prevStart = 0;
}
end = tween._startTime + (tween._totalDuration / tween._timeScale);
if (end > max) {
max = end;
}
tween = prev;
}
this._duration = this._totalDuration = max;
this._dirty = false;
}
return this._totalDuration;
}
return (value && this.totalDuration()) ? this.timeScale(this._totalDuration / value) : this;
};
p.paused = function(value) {
if (!value) { //if there's a pause directly at the spot from where we're unpausing, skip it.
var tween = this._first,
time = this._time;
while (tween) {
if (tween._startTime === time && tween.data === "isPause") {
tween._rawPrevTime = 0; //remember, _rawPrevTime is how zero-duration tweens/callbacks sense directionality and determine whether or not to fire. If _rawPrevTime is the same as _startTime on the next render, it won't fire.
}
tween = tween._next;
}
}
return Animation.prototype.paused.apply(this, arguments);
};
p.usesFrames = function() {
var tl = this._timeline;
while (tl._timeline) {
tl = tl._timeline;
}
return (tl === Animation._rootFramesTimeline);
};
p.rawTime = function() {
return this._paused ? this._totalTime : (this._timeline.rawTime() - this._startTime) * this._timeScale;
};
return TimelineLite;
}, true);
}); if (_gsScope._gsDefine) { _gsScope._gsQueue.pop()(); }
//export to AMD/RequireJS and CommonJS/Node (precursor to full modular build system coming at a later date)
(function(name) {
"use strict";
var getGlobal = function() {
return (_gsScope.GreenSockGlobals || _gsScope)[name];
};
if (typeof(define) === "function" && define.amd) { //AMD
define(["TweenLite"], getGlobal);
} else if (typeof(module) !== "undefined" && module.exports) { //node
require("./TweenLite.js"); //dependency
module.exports = getGlobal();
}
}("TimelineLite"));
/*!
* VERSION: 1.19.0
* DATE: 2016-07-16
* UPDATES AND DOCS AT: http://greensock.com
*
* @license Copyright (c) 2008-2016, GreenSock. All rights reserved.
* This work is subject to the terms at http://greensock.com/standard-license or for
* Club GreenSock members, the software agreement that was issued with your membership.
*
* @author: Jack Doyle, jack@greensock.com
*/
(function(window, moduleName) {
"use strict";
var _exports = {},
_globals = window.GreenSockGlobals = window.GreenSockGlobals || window;
if (_globals.TweenLite) {
return; //in case the core set of classes is already loaded, don't instantiate twice.
}
var _namespace = function(ns) {
var a = ns.split("."),
p = _globals, i;
for (i = 0; i < a.length; i++) {
p[a[i]] = p = p[a[i]] || {};
}
return p;
},
gs = _namespace("com.greensock"),
_tinyNum = 0.0000000001,
_slice = function(a) { //don't use Array.prototype.slice.call(target, 0) because that doesn't work in IE8 with a NodeList that's returned by querySelectorAll()
var b = [],
l = a.length,
i;
for (i = 0; i !== l; b.push(a[i++])) {}
return b;
},
_emptyFunc = function() {},
_isArray = (function() { //works around issues in iframe environments where the Array global isn't shared, thus if the object originates in a different window/iframe, "(obj instanceof Array)" will evaluate false. We added some speed optimizations to avoid Object.prototype.toString.call() unless it's absolutely necessary because it's VERY slow (like 20x slower)
var toString = Object.prototype.toString,
array = toString.call([]);
return function(obj) {
return obj != null && (obj instanceof Array || (typeof(obj) === "object" && !!obj.push && toString.call(obj) === array));
};
}()),
a, i, p, _ticker, _tickerActive,
_defLookup = {},
/**
* @constructor
* Defines a GreenSock class, optionally with an array of dependencies that must be instantiated first and passed into the definition.
* This allows users to load GreenSock JS files in any order even if they have interdependencies (like CSSPlugin extends TweenPlugin which is
* inside TweenLite.js, but if CSSPlugin is loaded first, it should wait to run its code until TweenLite.js loads and instantiates TweenPlugin
* and then pass TweenPlugin to CSSPlugin's definition). This is all done automatically and internally.
*
* Every definition will be added to a "com.greensock" global object (typically window, but if a window.GreenSockGlobals object is found,
* it will go there as of v1.7). For example, TweenLite will be found at window.com.greensock.TweenLite and since it's a global class that should be available anywhere,
* it is ALSO referenced at window.TweenLite. However some classes aren't considered global, like the base com.greensock.core.Animation class, so
* those will only be at the package like window.com.greensock.core.Animation. Again, if you define a GreenSockGlobals object on the window, everything
* gets tucked neatly inside there instead of on the window directly. This allows you to do advanced things like load multiple versions of GreenSock
* files and put them into distinct objects (imagine a banner ad uses a newer version but the main site uses an older one). In that case, you could
* sandbox the banner one like:
*
*
*
*
*
*
*
* @param {!string} ns The namespace of the class definition, leaving off "com.greensock." as that's assumed. For example, "TweenLite" or "plugins.CSSPlugin" or "easing.Back".
* @param {!Array.