jquery.touchSwipe.js 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109
  1. /*!
  2. * @fileOverview TouchSwipe - jQuery Plugin
  3. * @version 1.6.18
  4. *
  5. * @author Matt Bryson http://www.github.com/mattbryson
  6. * @see https://github.com/mattbryson/TouchSwipe-Jquery-Plugin
  7. * @see http://labs.rampinteractive.co.uk/touchSwipe/
  8. * @see http://plugins.jquery.com/project/touchSwipe
  9. * @license
  10. * Copyright (c) 2010-2015 Matt Bryson
  11. * Dual licensed under the MIT or GPL Version 2 licenses.
  12. *
  13. */
  14. /*
  15. *
  16. * Changelog
  17. * $Date: 2010-12-12 (Wed, 12 Dec 2010) $
  18. * $version: 1.0.0
  19. * $version: 1.0.1 - removed multibyte comments
  20. *
  21. * $Date: 2011-21-02 (Mon, 21 Feb 2011) $
  22. * $version: 1.1.0 - added allowPageScroll property to allow swiping and scrolling of page
  23. * - changed handler signatures so one handler can be used for multiple events
  24. * $Date: 2011-23-02 (Wed, 23 Feb 2011) $
  25. * $version: 1.2.0 - added click handler. This is fired if the user simply clicks and does not swipe. The event object and click target are passed to handler.
  26. * - If you use the http://code.google.com/p/jquery-ui-for-ipad-and-iphone/ plugin, you can also assign jQuery mouse events to children of a touchSwipe object.
  27. * $version: 1.2.1 - removed console log!
  28. *
  29. * $version: 1.2.2 - Fixed bug where scope was not preserved in callback methods.
  30. *
  31. * $Date: 2011-28-04 (Thurs, 28 April 2011) $
  32. * $version: 1.2.4 - Changed licence terms to be MIT or GPL inline with jQuery. Added check for support of touch events to stop non compatible browsers erroring.
  33. *
  34. * $Date: 2011-27-09 (Tues, 27 September 2011) $
  35. * $version: 1.2.5 - Added support for testing swipes with mouse on desktop browser (thanks to https://github.com/joelhy)
  36. *
  37. * $Date: 2012-14-05 (Mon, 14 May 2012) $
  38. * $version: 1.2.6 - Added timeThreshold between start and end touch, so user can ignore slow swipes (thanks to Mark Chase). Default is null, all swipes are detected
  39. *
  40. * $Date: 2012-05-06 (Tues, 05 June 2012) $
  41. * $version: 1.2.7 - Changed time threshold to have null default for backwards compatibility. Added duration param passed back in events, and refactored how time is handled.
  42. *
  43. * $Date: 2012-05-06 (Tues, 05 June 2012) $
  44. * $version: 1.2.8 - Added the possibility to return a value like null or false in the trigger callback. In that way we can control when the touch start/move should take effect or not (simply by returning in some cases return null; or return false;) This effects the ontouchstart/ontouchmove event.
  45. *
  46. * $Date: 2012-06-06 (Wed, 06 June 2012) $
  47. * $version: 1.3.0 - Refactored whole plugin to allow for methods to be executed, as well as exposed defaults for user override. Added 'enable', 'disable', and 'destroy' methods
  48. *
  49. * $Date: 2012-05-06 (Fri, 05 June 2012) $
  50. * $version: 1.3.1 - Bug fixes - bind() with false as last argument is no longer supported in jQuery 1.6, also, if you just click, the duration is now returned correctly.
  51. *
  52. * $Date: 2012-29-07 (Sun, 29 July 2012) $
  53. * $version: 1.3.2 - Added fallbackToMouseEvents option to NOT capture mouse events on non touch devices.
  54. * - Added "all" fingers value to the fingers property, so any combination of fingers triggers the swipe, allowing event handlers to check the finger count
  55. *
  56. * $Date: 2012-09-08 (Thurs, 9 Aug 2012) $
  57. * $version: 1.3.3 - Code tidy prep for minefied version
  58. *
  59. * $Date: 2012-04-10 (wed, 4 Oct 2012) $
  60. * $version: 1.4.0 - Added pinch support, pinchIn and pinchOut
  61. *
  62. * $Date: 2012-11-10 (Thurs, 11 Oct 2012) $
  63. * $version: 1.5.0 - Added excludedElements, a jquery selector that specifies child elements that do NOT trigger swipes. By default, this is .noSwipe
  64. *
  65. * $Date: 2012-22-10 (Mon, 22 Oct 2012) $
  66. * $version: 1.5.1 - Fixed bug with jQuery 1.8 and trailing comma in excludedElements
  67. * - Fixed bug with IE and eventPreventDefault()
  68. * $Date: 2013-01-12 (Fri, 12 Jan 2013) $
  69. * $version: 1.6.0 - Fixed bugs with pinching, mainly when both pinch and swipe enabled, as well as adding time threshold for multifinger gestures, so releasing one finger beofre the other doesnt trigger as single finger gesture.
  70. * - made the demo site all static local HTML pages so they can be run locally by a developer
  71. * - added jsDoc comments and added documentation for the plugin
  72. * - code tidy
  73. * - added triggerOnTouchLeave property that will end the event when the user swipes off the element.
  74. * $Date: 2013-03-23 (Sat, 23 Mar 2013) $
  75. * $version: 1.6.1 - Added support for ie8 touch events
  76. * $version: 1.6.2 - Added support for events binding with on / off / bind in jQ for all callback names.
  77. * - Deprecated the 'click' handler in favour of tap.
  78. * - added cancelThreshold property
  79. * - added option method to update init options at runtime
  80. * $version 1.6.3 - added doubletap, longtap events and longTapThreshold, doubleTapThreshold property
  81. *
  82. * $Date: 2013-04-04 (Thurs, 04 April 2013) $
  83. * $version 1.6.4 - Fixed bug with cancelThreshold introduced in 1.6.3, where swipe status no longer fired start event, and stopped once swiping back.
  84. *
  85. * $Date: 2013-08-24 (Sat, 24 Aug 2013) $
  86. * $version 1.6.5 - Merged a few pull requests fixing various bugs, added AMD support.
  87. *
  88. * $Date: 2014-06-04 (Wed, 04 June 2014) $
  89. * $version 1.6.6 - Merge of pull requests.
  90. * - IE10 touch support
  91. * - Only prevent default event handling on valid swipe
  92. * - Separate license/changelog comment
  93. * - Detect if the swipe is valid at the end of the touch event.
  94. * - Pass fingerdata to event handlers.
  95. * - Add 'hold' gesture
  96. * - Be more tolerant about the tap distance
  97. * - Typos and minor fixes
  98. *
  99. * $Date: 2015-22-01 (Thurs, 22 Jan 2015) $
  100. * $version 1.6.7 - Added patch from https://github.com/mattbryson/TouchSwipe-Jquery-Plugin/issues/206 to fix memory leak
  101. *
  102. * $Date: 2015-2-2 (Mon, 2 Feb 2015) $
  103. * $version 1.6.8 - Added preventDefaultEvents option to proxy events regardless.
  104. * - Fixed issue with swipe and pinch not triggering at the same time
  105. *
  106. * $Date: 2015-9-6 (Tues, 9 June 2015) $
  107. * $version 1.6.9 - Added PR from jdalton/hybrid to fix pointer events
  108. * - Added scrolling demo
  109. * - Added version property to plugin
  110. *
  111. * $Date: 2015-1-10 (Wed, 1 October 2015) $
  112. * $version 1.6.10 - Added PR from beatspace to fix tap events
  113. * $version 1.6.11 - Added PRs from indri-indri ( Doc tidyup), kkirsche ( Bower tidy up ), UziTech (preventDefaultEvents fixes )
  114. * - Allowed setting multiple options via .swipe("options", options_hash) and more simply .swipe(options_hash) or exisitng instances
  115. * $version 1.6.12 - Fixed bug with multi finger releases above 2 not triggering events
  116. *
  117. * $Date: 2015-12-18 (Fri, 18 December 2015) $
  118. * $version 1.6.13 - Added PRs
  119. * - Fixed #267 allowPageScroll not working correctly
  120. * $version 1.6.14 - Fixed #220 / #248 doubletap not firing with swipes, #223 commonJS compatible
  121. * $version 1.6.15 - More bug fixes
  122. *
  123. * $Date: 2016-04-29 (Fri, 29 April 2016) $
  124. * $version 1.6.16 - Swipes with 0 distance now allow default events to trigger. So tapping any form elements or A tags will allow default interaction, but swiping will trigger a swipe.
  125. Removed the a, input, select etc from the excluded Children list as the 0 distance tap solves that issue.
  126. * $Date: 2016-05-19 (Fri, 29 April 2016) $
  127. * $version 1.6.17 - Fixed context issue when calling instance methods via $("selector").swipe("method");
  128. * $version 1.6.18 - now honors fallbackToMouseEvents=false for MS Pointer events when a Mouse is used.
  129. */
  130. /**
  131. * See (http://jquery.com/).
  132. * @name $
  133. * @class
  134. * See the jQuery Library (http://jquery.com/) for full details. This just
  135. * documents the function and classes that are added to jQuery by this plug-in.
  136. */
  137. /**
  138. * See (http://jquery.com/)
  139. * @name fn
  140. * @class
  141. * See the jQuery Library (http://jquery.com/) for full details. This just
  142. * documents the function and classes that are added to jQuery by this plug-in.
  143. * @memberOf $
  144. */
  145. (function(factory) {
  146. if (typeof define === 'function' && define.amd && define.amd.jQuery) {
  147. // AMD. Register as anonymous module.
  148. define(['jquery'], factory);
  149. } else if (typeof module !== 'undefined' && module.exports) {
  150. // CommonJS Module
  151. factory(require("jquery"));
  152. } else {
  153. // Browser globals.
  154. factory(jQuery);
  155. }
  156. }(function($) {
  157. "use strict";
  158. //Constants
  159. var VERSION = "1.6.18",
  160. LEFT = "left",
  161. RIGHT = "right",
  162. UP = "up",
  163. DOWN = "down",
  164. IN = "in",
  165. OUT = "out",
  166. NONE = "none",
  167. AUTO = "auto",
  168. SWIPE = "swipe",
  169. PINCH = "pinch",
  170. TAP = "tap",
  171. DOUBLE_TAP = "doubletap",
  172. LONG_TAP = "longtap",
  173. HOLD = "hold",
  174. HORIZONTAL = "horizontal",
  175. VERTICAL = "vertical",
  176. ALL_FINGERS = "all",
  177. DOUBLE_TAP_THRESHOLD = 10,
  178. PHASE_START = "start",
  179. PHASE_MOVE = "move",
  180. PHASE_END = "end",
  181. PHASE_CANCEL = "cancel",
  182. SUPPORTS_TOUCH = 'ontouchstart' in window,
  183. SUPPORTS_POINTER_IE10 = window.navigator.msPointerEnabled && !window.navigator.pointerEnabled && !SUPPORTS_TOUCH,
  184. SUPPORTS_POINTER = (window.navigator.pointerEnabled || window.navigator.msPointerEnabled) && !SUPPORTS_TOUCH,
  185. PLUGIN_NS = 'TouchSwipe';
  186. /**
  187. * The default configuration, and available options to configure touch swipe with.
  188. * You can set the default values by updating any of the properties prior to instantiation.
  189. * @name $.fn.swipe.defaults
  190. * @namespace
  191. * @property {int} [fingers=1] The number of fingers to detect in a swipe. Any swipes that do not meet this requirement will NOT trigger swipe handlers.
  192. * @property {int} [threshold=75] The number of pixels that the user must move their finger by before it is considered a swipe.
  193. * @property {int} [cancelThreshold=null] The number of pixels that the user must move their finger back from the original swipe direction to cancel the gesture.
  194. * @property {int} [pinchThreshold=20] The number of pixels that the user must pinch their finger by before it is considered a pinch.
  195. * @property {int} [maxTimeThreshold=null] Time, in milliseconds, between touchStart and touchEnd must NOT exceed in order to be considered a swipe.
  196. * @property {int} [fingerReleaseThreshold=250] Time in milliseconds between releasing multiple fingers. If 2 fingers are down, and are released one after the other, if they are within this threshold, it counts as a simultaneous release.
  197. * @property {int} [longTapThreshold=500] Time in milliseconds between tap and release for a long tap
  198. * @property {int} [doubleTapThreshold=200] Time in milliseconds between 2 taps to count as a double tap
  199. * @property {function} [swipe=null] A handler to catch all swipes. See {@link $.fn.swipe#event:swipe}
  200. * @property {function} [swipeLeft=null] A handler that is triggered for "left" swipes. See {@link $.fn.swipe#event:swipeLeft}
  201. * @property {function} [swipeRight=null] A handler that is triggered for "right" swipes. See {@link $.fn.swipe#event:swipeRight}
  202. * @property {function} [swipeUp=null] A handler that is triggered for "up" swipes. See {@link $.fn.swipe#event:swipeUp}
  203. * @property {function} [swipeDown=null] A handler that is triggered for "down" swipes. See {@link $.fn.swipe#event:swipeDown}
  204. * @property {function} [swipeStatus=null] A handler triggered for every phase of the swipe. See {@link $.fn.swipe#event:swipeStatus}
  205. * @property {function} [pinchIn=null] A handler triggered for pinch in events. See {@link $.fn.swipe#event:pinchIn}
  206. * @property {function} [pinchOut=null] A handler triggered for pinch out events. See {@link $.fn.swipe#event:pinchOut}
  207. * @property {function} [pinchStatus=null] A handler triggered for every phase of a pinch. See {@link $.fn.swipe#event:pinchStatus}
  208. * @property {function} [tap=null] A handler triggered when a user just taps on the item, rather than swipes it. If they do not move, tap is triggered, if they do move, it is not.
  209. * @property {function} [doubleTap=null] A handler triggered when a user double taps on the item. The delay between taps can be set with the doubleTapThreshold property. See {@link $.fn.swipe.defaults#doubleTapThreshold}
  210. * @property {function} [longTap=null] A handler triggered when a user long taps on the item. The delay between start and end can be set with the longTapThreshold property. See {@link $.fn.swipe.defaults#longTapThreshold}
  211. * @property (function) [hold=null] A handler triggered when a user reaches longTapThreshold on the item. See {@link $.fn.swipe.defaults#longTapThreshold}
  212. * @property {boolean} [triggerOnTouchEnd=true] If true, the swipe events are triggered when the touch end event is received (user releases finger). If false, it will be triggered on reaching the threshold, and then cancel the touch event automatically.
  213. * @property {boolean} [triggerOnTouchLeave=false] If true, then when the user leaves the swipe object, the swipe will end and trigger appropriate handlers.
  214. * @property {string|undefined} [allowPageScroll='auto'] How the browser handles page scrolls when the user is swiping on a touchSwipe object. See {@link $.fn.swipe.pageScroll}. <br/><br/>
  215. <code>"auto"</code> : all undefined swipes will cause the page to scroll in that direction. <br/>
  216. <code>"none"</code> : the page will not scroll when user swipes. <br/>
  217. <code>"horizontal"</code> : will force page to scroll on horizontal swipes. <br/>
  218. <code>"vertical"</code> : will force page to scroll on vertical swipes. <br/>
  219. * @property {boolean} [fallbackToMouseEvents=true] If true mouse events are used when run on a non touch device, false will stop swipes being triggered by mouse events on non touch devices.
  220. * @property {string} [excludedElements=".noSwipe"] A jquery selector that specifies child elements that do NOT trigger swipes. By default this excludes elements with the class .noSwipe .
  221. * @property {boolean} [preventDefaultEvents=true] by default default events are cancelled, so the page doesn't move. You can disable this so both native events fire as well as your handlers.
  222. */
  223. var defaults = {
  224. fingers: 1,
  225. threshold: 75,
  226. cancelThreshold: null,
  227. pinchThreshold: 20,
  228. maxTimeThreshold: null,
  229. fingerReleaseThreshold: 250,
  230. longTapThreshold: 500,
  231. doubleTapThreshold: 200,
  232. swipe: null,
  233. swipeLeft: null,
  234. swipeRight: null,
  235. swipeUp: null,
  236. swipeDown: null,
  237. swipeStatus: null,
  238. pinchIn: null,
  239. pinchOut: null,
  240. pinchStatus: null,
  241. click: null, //Deprecated since 1.6.2
  242. tap: null,
  243. doubleTap: null,
  244. longTap: null,
  245. hold: null,
  246. triggerOnTouchEnd: true,
  247. triggerOnTouchLeave: false,
  248. allowPageScroll: "auto",
  249. fallbackToMouseEvents: true,
  250. excludedElements: ".noSwipe",
  251. preventDefaultEvents: true
  252. };
  253. /**
  254. * Applies TouchSwipe behaviour to one or more jQuery objects.
  255. * The TouchSwipe plugin can be instantiated via this method, or methods within
  256. * TouchSwipe can be executed via this method as per jQuery plugin architecture.
  257. * An existing plugin can have its options changed simply by re calling .swipe(options)
  258. * @see TouchSwipe
  259. * @class
  260. * @param {Mixed} method If the current DOMNode is a TouchSwipe object, and <code>method</code> is a TouchSwipe method, then
  261. * the <code>method</code> is executed, and any following arguments are passed to the TouchSwipe method.
  262. * If <code>method</code> is an object, then the TouchSwipe class is instantiated on the current DOMNode, passing the
  263. * configuration properties defined in the object. See TouchSwipe
  264. *
  265. */
  266. $.fn.swipe = function(method) {
  267. var $this = $(this),
  268. plugin = $this.data(PLUGIN_NS);
  269. //Check if we are already instantiated and trying to execute a method
  270. if (plugin && typeof method === 'string') {
  271. if (plugin[method]) {
  272. return plugin[method].apply(plugin, Array.prototype.slice.call(arguments, 1));
  273. } else {
  274. $.error('Method ' + method + ' does not exist on jQuery.swipe');
  275. }
  276. }
  277. //Else update existing plugin with new options hash
  278. else if (plugin && typeof method === 'object') {
  279. plugin['option'].apply(plugin, arguments);
  280. }
  281. //Else not instantiated and trying to pass init object (or nothing)
  282. else if (!plugin && (typeof method === 'object' || !method)) {
  283. return init.apply(this, arguments);
  284. }
  285. return $this;
  286. };
  287. /**
  288. * The version of the plugin
  289. * @readonly
  290. */
  291. $.fn.swipe.version = VERSION;
  292. //Expose our defaults so a user could override the plugin defaults
  293. $.fn.swipe.defaults = defaults;
  294. /**
  295. * The phases that a touch event goes through. The <code>phase</code> is passed to the event handlers.
  296. * These properties are read only, attempting to change them will not alter the values passed to the event handlers.
  297. * @namespace
  298. * @readonly
  299. * @property {string} PHASE_START Constant indicating the start phase of the touch event. Value is <code>"start"</code>.
  300. * @property {string} PHASE_MOVE Constant indicating the move phase of the touch event. Value is <code>"move"</code>.
  301. * @property {string} PHASE_END Constant indicating the end phase of the touch event. Value is <code>"end"</code>.
  302. * @property {string} PHASE_CANCEL Constant indicating the cancel phase of the touch event. Value is <code>"cancel"</code>.
  303. */
  304. $.fn.swipe.phases = {
  305. PHASE_START: PHASE_START,
  306. PHASE_MOVE: PHASE_MOVE,
  307. PHASE_END: PHASE_END,
  308. PHASE_CANCEL: PHASE_CANCEL
  309. };
  310. /**
  311. * The direction constants that are passed to the event handlers.
  312. * These properties are read only, attempting to change them will not alter the values passed to the event handlers.
  313. * @namespace
  314. * @readonly
  315. * @property {string} LEFT Constant indicating the left direction. Value is <code>"left"</code>.
  316. * @property {string} RIGHT Constant indicating the right direction. Value is <code>"right"</code>.
  317. * @property {string} UP Constant indicating the up direction. Value is <code>"up"</code>.
  318. * @property {string} DOWN Constant indicating the down direction. Value is <code>"cancel"</code>.
  319. * @property {string} IN Constant indicating the in direction. Value is <code>"in"</code>.
  320. * @property {string} OUT Constant indicating the out direction. Value is <code>"out"</code>.
  321. */
  322. $.fn.swipe.directions = {
  323. LEFT: LEFT,
  324. RIGHT: RIGHT,
  325. UP: UP,
  326. DOWN: DOWN,
  327. IN: IN,
  328. OUT: OUT
  329. };
  330. /**
  331. * The page scroll constants that can be used to set the value of <code>allowPageScroll</code> option
  332. * These properties are read only
  333. * @namespace
  334. * @readonly
  335. * @see $.fn.swipe.defaults#allowPageScroll
  336. * @property {string} NONE Constant indicating no page scrolling is allowed. Value is <code>"none"</code>.
  337. * @property {string} HORIZONTAL Constant indicating horizontal page scrolling is allowed. Value is <code>"horizontal"</code>.
  338. * @property {string} VERTICAL Constant indicating vertical page scrolling is allowed. Value is <code>"vertical"</code>.
  339. * @property {string} AUTO Constant indicating either horizontal or vertical will be allowed, depending on the swipe handlers registered. Value is <code>"auto"</code>.
  340. */
  341. $.fn.swipe.pageScroll = {
  342. NONE: NONE,
  343. HORIZONTAL: HORIZONTAL,
  344. VERTICAL: VERTICAL,
  345. AUTO: AUTO
  346. };
  347. /**
  348. * Constants representing the number of fingers used in a swipe. These are used to set both the value of <code>fingers</code> in the
  349. * options object, as well as the value of the <code>fingers</code> event property.
  350. * These properties are read only, attempting to change them will not alter the values passed to the event handlers.
  351. * @namespace
  352. * @readonly
  353. * @see $.fn.swipe.defaults#fingers
  354. * @property {string} ONE Constant indicating 1 finger is to be detected / was detected. Value is <code>1</code>.
  355. * @property {string} TWO Constant indicating 2 fingers are to be detected / were detected. Value is <code>2</code>.
  356. * @property {string} THREE Constant indicating 3 finger are to be detected / were detected. Value is <code>3</code>.
  357. * @property {string} FOUR Constant indicating 4 finger are to be detected / were detected. Not all devices support this. Value is <code>4</code>.
  358. * @property {string} FIVE Constant indicating 5 finger are to be detected / were detected. Not all devices support this. Value is <code>5</code>.
  359. * @property {string} ALL Constant indicating any combination of finger are to be detected. Value is <code>"all"</code>.
  360. */
  361. $.fn.swipe.fingers = {
  362. ONE: 1,
  363. TWO: 2,
  364. THREE: 3,
  365. FOUR: 4,
  366. FIVE: 5,
  367. ALL: ALL_FINGERS
  368. };
  369. /**
  370. * Initialise the plugin for each DOM element matched
  371. * This creates a new instance of the main TouchSwipe class for each DOM element, and then
  372. * saves a reference to that instance in the elements data property.
  373. * @internal
  374. */
  375. function init(options) {
  376. //Prep and extend the options
  377. if (options && (options.allowPageScroll === undefined && (options.swipe !== undefined || options.swipeStatus !== undefined))) {
  378. options.allowPageScroll = NONE;
  379. }
  380. //Check for deprecated options
  381. //Ensure that any old click handlers are assigned to the new tap, unless we have a tap
  382. if (options.click !== undefined && options.tap === undefined) {
  383. options.tap = options.click;
  384. }
  385. if (!options) {
  386. options = {};
  387. }
  388. //pass empty object so we dont modify the defaults
  389. options = $.extend({}, $.fn.swipe.defaults, options);
  390. //For each element instantiate the plugin
  391. return this.each(function() {
  392. var $this = $(this);
  393. //Check we havent already initialised the plugin
  394. var plugin = $this.data(PLUGIN_NS);
  395. if (!plugin) {
  396. plugin = new TouchSwipe(this, options);
  397. $this.data(PLUGIN_NS, plugin);
  398. }
  399. });
  400. }
  401. /**
  402. * Main TouchSwipe Plugin Class.
  403. * Do not use this to construct your TouchSwipe object, use the jQuery plugin method $.fn.swipe(); {@link $.fn.swipe}
  404. * @private
  405. * @name TouchSwipe
  406. * @param {DOMNode} element The HTML DOM object to apply to plugin to
  407. * @param {Object} options The options to configure the plugin with. @link {$.fn.swipe.defaults}
  408. * @see $.fh.swipe.defaults
  409. * @see $.fh.swipe
  410. * @class
  411. */
  412. function TouchSwipe(element, options) {
  413. //take a local/instacne level copy of the options - should make it this.options really...
  414. var options = $.extend({}, options);
  415. var useTouchEvents = (SUPPORTS_TOUCH || SUPPORTS_POINTER || !options.fallbackToMouseEvents),
  416. START_EV = useTouchEvents ? (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerDown' : 'pointerdown') : 'touchstart') : 'mousedown',
  417. MOVE_EV = useTouchEvents ? (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerMove' : 'pointermove') : 'touchmove') : 'mousemove',
  418. END_EV = useTouchEvents ? (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerUp' : 'pointerup') : 'touchend') : 'mouseup',
  419. LEAVE_EV = useTouchEvents ? (SUPPORTS_POINTER ? 'mouseleave' : null) : 'mouseleave', //we manually detect leave on touch devices, so null event here
  420. CANCEL_EV = (SUPPORTS_POINTER ? (SUPPORTS_POINTER_IE10 ? 'MSPointerCancel' : 'pointercancel') : 'touchcancel');
  421. //touch properties
  422. var distance = 0,
  423. direction = null,
  424. currentDirection = null,
  425. duration = 0,
  426. startTouchesDistance = 0,
  427. endTouchesDistance = 0,
  428. pinchZoom = 1,
  429. pinchDistance = 0,
  430. pinchDirection = 0,
  431. maximumsMap = null;
  432. //jQuery wrapped element for this instance
  433. var $element = $(element);
  434. //Current phase of th touch cycle
  435. var phase = "start";
  436. // the current number of fingers being used.
  437. var fingerCount = 0;
  438. //track mouse points / delta
  439. var fingerData = {};
  440. //track times
  441. var startTime = 0,
  442. endTime = 0,
  443. previousTouchEndTime = 0,
  444. fingerCountAtRelease = 0,
  445. doubleTapStartTime = 0;
  446. //Timeouts
  447. var singleTapTimeout = null,
  448. holdTimeout = null;
  449. // Add gestures to all swipable areas if supported
  450. try {
  451. $element.bind(START_EV, touchStart);
  452. $element.bind(CANCEL_EV, touchCancel);
  453. } catch (e) {
  454. $.error('events not supported ' + START_EV + ',' + CANCEL_EV + ' on jQuery.swipe');
  455. }
  456. //
  457. //Public methods
  458. //
  459. /**
  460. * re-enables the swipe plugin with the previous configuration
  461. * @function
  462. * @name $.fn.swipe#enable
  463. * @return {DOMNode} The Dom element that was registered with TouchSwipe
  464. * @example $("#element").swipe("enable");
  465. */
  466. this.enable = function() {
  467. //Incase we are already enabled, clean up...
  468. this.disable();
  469. $element.bind(START_EV, touchStart);
  470. $element.bind(CANCEL_EV, touchCancel);
  471. return $element;
  472. };
  473. /**
  474. * disables the swipe plugin
  475. * @function
  476. * @name $.fn.swipe#disable
  477. * @return {DOMNode} The Dom element that is now registered with TouchSwipe
  478. * @example $("#element").swipe("disable");
  479. */
  480. this.disable = function() {
  481. removeListeners();
  482. return $element;
  483. };
  484. /**
  485. * Destroy the swipe plugin completely. To use any swipe methods, you must re initialise the plugin.
  486. * @function
  487. * @name $.fn.swipe#destroy
  488. * @example $("#element").swipe("destroy");
  489. */
  490. this.destroy = function() {
  491. removeListeners();
  492. $element.data(PLUGIN_NS, null);
  493. $element = null;
  494. };
  495. /**
  496. * Allows run time updating of the swipe configuration options.
  497. * @function
  498. * @name $.fn.swipe#option
  499. * @param {String} property The option property to get or set, or a has of multiple options to set
  500. * @param {Object} [value] The value to set the property to
  501. * @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.
  502. * @example $("#element").swipe("option", "threshold"); // return the threshold
  503. * @example $("#element").swipe("option", "threshold", 100); // set the threshold after init
  504. * @example $("#element").swipe("option", {threshold:100, fingers:3} ); // set multiple properties after init
  505. * @example $("#element").swipe({threshold:100, fingers:3} ); // set multiple properties after init - the "option" method is optional!
  506. * @example $("#element").swipe("option"); // Return the current options hash
  507. * @see $.fn.swipe.defaults
  508. *
  509. */
  510. this.option = function(property, value) {
  511. if (typeof property === 'object') {
  512. options = $.extend(options, property);
  513. } else if (options[property] !== undefined) {
  514. if (value === undefined) {
  515. return options[property];
  516. } else {
  517. options[property] = value;
  518. }
  519. } else if (!property) {
  520. return options;
  521. } else {
  522. $.error('Option ' + property + ' does not exist on jQuery.swipe.options');
  523. }
  524. return null;
  525. }
  526. //
  527. // Private methods
  528. //
  529. //
  530. // EVENTS
  531. //
  532. /**
  533. * Event handler for a touch start event.
  534. * Stops the default click event from triggering and stores where we touched
  535. * @inner
  536. * @param {object} jqEvent The normalised jQuery event object.
  537. */
  538. function touchStart(jqEvent) {
  539. //If we already in a touch event (a finger already in use) then ignore subsequent ones..
  540. if (getTouchInProgress()) {
  541. return;
  542. }
  543. //Check if this element matches any in the excluded elements selectors, or its parent is excluded, if so, DON'T swipe
  544. if ($(jqEvent.target).closest(options.excludedElements, $element).length > 0) {
  545. return;
  546. }
  547. //As we use Jquery bind for events, we need to target the original event object
  548. //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
  549. var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent;
  550. //If we have a pointer event, whoes type is 'mouse' and we have said NO mouse events, then dont do anything.
  551. if(event.pointerType && event.pointerType=="mouse" && options.fallbackToMouseEvents==false) {
  552. return;
  553. };
  554. var ret,
  555. touches = event.touches,
  556. evt = touches ? touches[0] : event;
  557. phase = PHASE_START;
  558. //If we support touches, get the finger count
  559. if (touches) {
  560. // get the total number of fingers touching the screen
  561. fingerCount = touches.length;
  562. }
  563. //Else this is the desktop, so stop the browser from dragging content
  564. else if (options.preventDefaultEvents !== false) {
  565. jqEvent.preventDefault(); //call this on jq event so we are cross browser
  566. }
  567. //clear vars..
  568. distance = 0;
  569. direction = null;
  570. currentDirection=null;
  571. pinchDirection = null;
  572. duration = 0;
  573. startTouchesDistance = 0;
  574. endTouchesDistance = 0;
  575. pinchZoom = 1;
  576. pinchDistance = 0;
  577. maximumsMap = createMaximumsData();
  578. cancelMultiFingerRelease();
  579. //Create the default finger data
  580. createFingerData(0, evt);
  581. // check the number of fingers is what we are looking for, or we are capturing pinches
  582. if (!touches || (fingerCount === options.fingers || options.fingers === ALL_FINGERS) || hasPinches()) {
  583. // get the coordinates of the touch
  584. startTime = getTimeStamp();
  585. if (fingerCount == 2) {
  586. //Keep track of the initial pinch distance, so we can calculate the diff later
  587. //Store second finger data as start
  588. createFingerData(1, touches[1]);
  589. startTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start);
  590. }
  591. if (options.swipeStatus || options.pinchStatus) {
  592. ret = triggerHandler(event, phase);
  593. }
  594. } else {
  595. //A touch with more or less than the fingers we are looking for, so cancel
  596. ret = false;
  597. }
  598. //If we have a return value from the users handler, then return and cancel
  599. if (ret === false) {
  600. phase = PHASE_CANCEL;
  601. triggerHandler(event, phase);
  602. return ret;
  603. } else {
  604. if (options.hold) {
  605. holdTimeout = setTimeout($.proxy(function() {
  606. //Trigger the event
  607. $element.trigger('hold', [event.target]);
  608. //Fire the callback
  609. if (options.hold) {
  610. ret = options.hold.call($element, event, event.target);
  611. }
  612. }, this), options.longTapThreshold);
  613. }
  614. setTouchInProgress(true);
  615. }
  616. return null;
  617. };
  618. /**
  619. * Event handler for a touch move event.
  620. * If we change fingers during move, then cancel the event
  621. * @inner
  622. * @param {object} jqEvent The normalised jQuery event object.
  623. */
  624. function touchMove(jqEvent) {
  625. //As we use Jquery bind for events, we need to target the original event object
  626. //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
  627. var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent;
  628. //If we are ending, cancelling, or within the threshold of 2 fingers being released, don't track anything..
  629. if (phase === PHASE_END || phase === PHASE_CANCEL || inMultiFingerRelease())
  630. return;
  631. var ret,
  632. touches = event.touches,
  633. evt = touches ? touches[0] : event;
  634. //Update the finger data
  635. var currentFinger = updateFingerData(evt);
  636. endTime = getTimeStamp();
  637. if (touches) {
  638. fingerCount = touches.length;
  639. }
  640. if (options.hold) {
  641. clearTimeout(holdTimeout);
  642. }
  643. phase = PHASE_MOVE;
  644. //If we have 2 fingers get Touches distance as well
  645. if (fingerCount == 2) {
  646. //Keep track of the initial pinch distance, so we can calculate the diff later
  647. //We do this here as well as the start event, in case they start with 1 finger, and the press 2 fingers
  648. if (startTouchesDistance == 0) {
  649. //Create second finger if this is the first time...
  650. createFingerData(1, touches[1]);
  651. startTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start);
  652. } else {
  653. //Else just update the second finger
  654. updateFingerData(touches[1]);
  655. endTouchesDistance = calculateTouchesDistance(fingerData[0].end, fingerData[1].end);
  656. pinchDirection = calculatePinchDirection(fingerData[0].end, fingerData[1].end);
  657. }
  658. pinchZoom = calculatePinchZoom(startTouchesDistance, endTouchesDistance);
  659. pinchDistance = Math.abs(startTouchesDistance - endTouchesDistance);
  660. }
  661. if ((fingerCount === options.fingers || options.fingers === ALL_FINGERS) || !touches || hasPinches()) {
  662. //The overall direction of the swipe. From start to now.
  663. direction = calculateDirection(currentFinger.start, currentFinger.end);
  664. //The immediate direction of the swipe, direction between the last movement and this one.
  665. currentDirection = calculateDirection(currentFinger.last, currentFinger.end);
  666. //Check if we need to prevent default event (page scroll / pinch zoom) or not
  667. validateDefaultEvent(jqEvent, currentDirection);
  668. //Distance and duration are all off the main finger
  669. distance = calculateDistance(currentFinger.start, currentFinger.end);
  670. duration = calculateDuration();
  671. //Cache the maximum distance we made in this direction
  672. setMaxDistance(direction, distance);
  673. //Trigger status handler
  674. ret = triggerHandler(event, phase);
  675. //If we trigger end events when threshold are met, or trigger events when touch leaves element
  676. if (!options.triggerOnTouchEnd || options.triggerOnTouchLeave) {
  677. var inBounds = true;
  678. //If checking if we leave the element, run the bounds check (we can use touchleave as its not supported on webkit)
  679. if (options.triggerOnTouchLeave) {
  680. var bounds = getbounds(this);
  681. inBounds = isInBounds(currentFinger.end, bounds);
  682. }
  683. //Trigger end handles as we swipe if thresholds met or if we have left the element if the user has asked to check these..
  684. if (!options.triggerOnTouchEnd && inBounds) {
  685. phase = getNextPhase(PHASE_MOVE);
  686. }
  687. //We end if out of bounds here, so set current phase to END, and check if its modified
  688. else if (options.triggerOnTouchLeave && !inBounds) {
  689. phase = getNextPhase(PHASE_END);
  690. }
  691. if (phase == PHASE_CANCEL || phase == PHASE_END) {
  692. triggerHandler(event, phase);
  693. }
  694. }
  695. } else {
  696. phase = PHASE_CANCEL;
  697. triggerHandler(event, phase);
  698. }
  699. if (ret === false) {
  700. phase = PHASE_CANCEL;
  701. triggerHandler(event, phase);
  702. }
  703. }
  704. /**
  705. * Event handler for a touch end event.
  706. * Calculate the direction and trigger events
  707. * @inner
  708. * @param {object} jqEvent The normalised jQuery event object.
  709. */
  710. function touchEnd(jqEvent) {
  711. //As we use Jquery bind for events, we need to target the original event object
  712. //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
  713. var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent,
  714. touches = event.touches;
  715. //If we are still in a touch with the device wait a fraction and see if the other finger comes up
  716. //if it does within the threshold, then we treat it as a multi release, not a single release and end the touch / swipe
  717. if (touches) {
  718. if (touches.length && !inMultiFingerRelease()) {
  719. startMultiFingerRelease(event);
  720. return true;
  721. } else if (touches.length && inMultiFingerRelease()) {
  722. return true;
  723. }
  724. }
  725. //If a previous finger has been released, check how long ago, if within the threshold, then assume it was a multifinger release.
  726. //This is used to allow 2 fingers to release fractionally after each other, whilst maintaining the event as containing 2 fingers, not 1
  727. if (inMultiFingerRelease()) {
  728. fingerCount = fingerCountAtRelease;
  729. }
  730. //Set end of swipe
  731. endTime = getTimeStamp();
  732. //Get duration incase move was never fired
  733. duration = calculateDuration();
  734. //If we trigger handlers at end of swipe OR, we trigger during, but they didnt trigger and we are still in the move phase
  735. if (didSwipeBackToCancel() || !validateSwipeDistance()) {
  736. phase = PHASE_CANCEL;
  737. triggerHandler(event, phase);
  738. } else if (options.triggerOnTouchEnd || (options.triggerOnTouchEnd === false && phase === PHASE_MOVE)) {
  739. //call this on jq event so we are cross browser
  740. if (options.preventDefaultEvents !== false) {
  741. jqEvent.preventDefault();
  742. }
  743. phase = PHASE_END;
  744. triggerHandler(event, phase);
  745. }
  746. //Special cases - A tap should always fire on touch end regardless,
  747. //So here we manually trigger the tap end handler by itself
  748. //We dont run trigger handler as it will re-trigger events that may have fired already
  749. else if (!options.triggerOnTouchEnd && hasTap()) {
  750. //Trigger the pinch events...
  751. phase = PHASE_END;
  752. triggerHandlerForGesture(event, phase, TAP);
  753. } else if (phase === PHASE_MOVE) {
  754. phase = PHASE_CANCEL;
  755. triggerHandler(event, phase);
  756. }
  757. setTouchInProgress(false);
  758. return null;
  759. }
  760. /**
  761. * Event handler for a touch cancel event.
  762. * Clears current vars
  763. * @inner
  764. */
  765. function touchCancel() {
  766. // reset the variables back to default values
  767. fingerCount = 0;
  768. endTime = 0;
  769. startTime = 0;
  770. startTouchesDistance = 0;
  771. endTouchesDistance = 0;
  772. pinchZoom = 1;
  773. //If we were in progress of tracking a possible multi touch end, then re set it.
  774. cancelMultiFingerRelease();
  775. setTouchInProgress(false);
  776. }
  777. /**
  778. * Event handler for a touch leave event.
  779. * This is only triggered on desktops, in touch we work this out manually
  780. * as the touchleave event is not supported in webkit
  781. * @inner
  782. */
  783. function touchLeave(jqEvent) {
  784. //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.
  785. var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent;
  786. //If we have the trigger on leave property set....
  787. if (options.triggerOnTouchLeave) {
  788. phase = getNextPhase(PHASE_END);
  789. triggerHandler(event, phase);
  790. }
  791. }
  792. /**
  793. * Removes all listeners that were associated with the plugin
  794. * @inner
  795. */
  796. function removeListeners() {
  797. $element.unbind(START_EV, touchStart);
  798. $element.unbind(CANCEL_EV, touchCancel);
  799. $element.unbind(MOVE_EV, touchMove);
  800. $element.unbind(END_EV, touchEnd);
  801. //we only have leave events on desktop, we manually calculate leave on touch as its not supported in webkit
  802. if (LEAVE_EV) {
  803. $element.unbind(LEAVE_EV, touchLeave);
  804. }
  805. setTouchInProgress(false);
  806. }
  807. /**
  808. * Checks if the time and distance thresholds have been met, and if so then the appropriate handlers are fired.
  809. */
  810. function getNextPhase(currentPhase) {
  811. var nextPhase = currentPhase;
  812. // Ensure we have valid swipe (under time and over distance and check if we are out of bound...)
  813. var validTime = validateSwipeTime();
  814. var validDistance = validateSwipeDistance();
  815. var didCancel = didSwipeBackToCancel();
  816. //If we have exceeded our time, then cancel
  817. if (!validTime || didCancel) {
  818. nextPhase = PHASE_CANCEL;
  819. }
  820. //Else if we are moving, and have reached distance then end
  821. else if (validDistance && currentPhase == PHASE_MOVE && (!options.triggerOnTouchEnd || options.triggerOnTouchLeave)) {
  822. nextPhase = PHASE_END;
  823. }
  824. //Else if we have ended by leaving and didn't reach distance, then cancel
  825. else if (!validDistance && currentPhase == PHASE_END && options.triggerOnTouchLeave) {
  826. nextPhase = PHASE_CANCEL;
  827. }
  828. return nextPhase;
  829. }
  830. /**
  831. * Trigger the relevant event handler
  832. * 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"
  833. * @param {object} event the original event object
  834. * @param {string} phase the phase of the swipe (start, end cancel etc) {@link $.fn.swipe.phases}
  835. * @inner
  836. */
  837. function triggerHandler(event, phase) {
  838. var ret,
  839. touches = event.touches;
  840. // SWIPE GESTURES
  841. if (didSwipe() || hasSwipes()) {
  842. ret = triggerHandlerForGesture(event, phase, SWIPE);
  843. }
  844. // PINCH GESTURES (if the above didn't cancel)
  845. if ((didPinch() || hasPinches()) && ret !== false) {
  846. ret = triggerHandlerForGesture(event, phase, PINCH);
  847. }
  848. // CLICK / TAP (if the above didn't cancel)
  849. if (didDoubleTap() && ret !== false) {
  850. //Trigger the tap events...
  851. ret = triggerHandlerForGesture(event, phase, DOUBLE_TAP);
  852. }
  853. // CLICK / TAP (if the above didn't cancel)
  854. else if (didLongTap() && ret !== false) {
  855. //Trigger the tap events...
  856. ret = triggerHandlerForGesture(event, phase, LONG_TAP);
  857. }
  858. // CLICK / TAP (if the above didn't cancel)
  859. else if (didTap() && ret !== false) {
  860. //Trigger the tap event..
  861. ret = triggerHandlerForGesture(event, phase, TAP);
  862. }
  863. // If we are cancelling the gesture, then manually trigger the reset handler
  864. if (phase === PHASE_CANCEL) {
  865. touchCancel(event);
  866. }
  867. // If we are ending the gesture, then manually trigger the reset handler IF all fingers are off
  868. if (phase === PHASE_END) {
  869. //If we support touch, then check that all fingers are off before we cancel
  870. if (touches) {
  871. if (!touches.length) {
  872. touchCancel(event);
  873. }
  874. } else {
  875. touchCancel(event);
  876. }
  877. }
  878. return ret;
  879. }
  880. /**
  881. * Trigger the relevant event handler
  882. * 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"
  883. * @param {object} event the original event object
  884. * @param {string} phase the phase of the swipe (start, end cancel etc) {@link $.fn.swipe.phases}
  885. * @param {string} gesture the gesture to trigger a handler for : PINCH or SWIPE {@link $.fn.swipe.gestures}
  886. * @return Boolean False, to indicate that the event should stop propagation, or void.
  887. * @inner
  888. */
  889. function triggerHandlerForGesture(event, phase, gesture) {
  890. var ret;
  891. //SWIPES....
  892. if (gesture == SWIPE) {
  893. //Trigger status every time..
  894. $element.trigger('swipeStatus', [phase, direction || null, distance || 0, duration || 0, fingerCount, fingerData, currentDirection]);
  895. if (options.swipeStatus) {
  896. ret = options.swipeStatus.call($element, event, phase, direction || null, distance || 0, duration || 0, fingerCount, fingerData, currentDirection);
  897. //If the status cancels, then dont run the subsequent event handlers..
  898. if (ret === false) return false;
  899. }
  900. if (phase == PHASE_END && validateSwipe()) {
  901. //Cancel any taps that were in progress...
  902. clearTimeout(singleTapTimeout);
  903. clearTimeout(holdTimeout);
  904. $element.trigger('swipe', [direction, distance, duration, fingerCount, fingerData, currentDirection]);
  905. if (options.swipe) {
  906. ret = options.swipe.call($element, event, direction, distance, duration, fingerCount, fingerData, currentDirection);
  907. //If the status cancels, then dont run the subsequent event handlers..
  908. if (ret === false) return false;
  909. }
  910. //trigger direction specific event handlers
  911. switch (direction) {
  912. case LEFT:
  913. $element.trigger('swipeLeft', [direction, distance, duration, fingerCount, fingerData, currentDirection]);
  914. if (options.swipeLeft) {
  915. ret = options.swipeLeft.call($element, event, direction, distance, duration, fingerCount, fingerData, currentDirection);
  916. }
  917. break;
  918. case RIGHT:
  919. $element.trigger('swipeRight', [direction, distance, duration, fingerCount, fingerData, currentDirection]);
  920. if (options.swipeRight) {
  921. ret = options.swipeRight.call($element, event, direction, distance, duration, fingerCount, fingerData, currentDirection);
  922. }
  923. break;
  924. case UP:
  925. $element.trigger('swipeUp', [direction, distance, duration, fingerCount, fingerData, currentDirection]);
  926. if (options.swipeUp) {
  927. ret = options.swipeUp.call($element, event, direction, distance, duration, fingerCount, fingerData, currentDirection);
  928. }
  929. break;
  930. case DOWN:
  931. $element.trigger('swipeDown', [direction, distance, duration, fingerCount, fingerData, currentDirection]);
  932. if (options.swipeDown) {
  933. ret = options.swipeDown.call($element, event, direction, distance, duration, fingerCount, fingerData, currentDirection);
  934. }
  935. break;
  936. }
  937. }
  938. }
  939. //PINCHES....
  940. if (gesture == PINCH) {
  941. $element.trigger('pinchStatus', [phase, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData]);
  942. if (options.pinchStatus) {
  943. ret = options.pinchStatus.call($element, event, phase, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData);
  944. //If the status cancels, then dont run the subsequent event handlers..
  945. if (ret === false) return false;
  946. }
  947. if (phase == PHASE_END && validatePinch()) {
  948. switch (pinchDirection) {
  949. case IN:
  950. $element.trigger('pinchIn', [pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData]);
  951. if (options.pinchIn) {
  952. ret = options.pinchIn.call($element, event, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData);
  953. }
  954. break;
  955. case OUT:
  956. $element.trigger('pinchOut', [pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData]);
  957. if (options.pinchOut) {
  958. ret = options.pinchOut.call($element, event, pinchDirection || null, pinchDistance || 0, duration || 0, fingerCount, pinchZoom, fingerData);
  959. }
  960. break;
  961. }
  962. }
  963. }
  964. if (gesture == TAP) {
  965. if (phase === PHASE_CANCEL || phase === PHASE_END) {
  966. clearTimeout(singleTapTimeout);
  967. clearTimeout(holdTimeout);
  968. //If we are also looking for doubelTaps, wait incase this is one...
  969. if (hasDoubleTap() && !inDoubleTap()) {
  970. doubleTapStartTime = getTimeStamp();
  971. //Now wait for the double tap timeout, and trigger this single tap
  972. //if its not cancelled by a double tap
  973. singleTapTimeout = setTimeout($.proxy(function() {
  974. doubleTapStartTime = null;
  975. $element.trigger('tap', [event.target]);
  976. if (options.tap) {
  977. ret = options.tap.call($element, event, event.target);
  978. }
  979. }, this), options.doubleTapThreshold);
  980. } else {
  981. doubleTapStartTime = null;
  982. $element.trigger('tap', [event.target]);
  983. if (options.tap) {
  984. ret = options.tap.call($element, event, event.target);
  985. }
  986. }
  987. }
  988. } else if (gesture == DOUBLE_TAP) {
  989. if (phase === PHASE_CANCEL || phase === PHASE_END) {
  990. clearTimeout(singleTapTimeout);
  991. clearTimeout(holdTimeout);
  992. doubleTapStartTime = null;
  993. $element.trigger('doubletap', [event.target]);
  994. if (options.doubleTap) {
  995. ret = options.doubleTap.call($element, event, event.target);
  996. }
  997. }
  998. } else if (gesture == LONG_TAP) {
  999. if (phase === PHASE_CANCEL || phase === PHASE_END) {
  1000. clearTimeout(singleTapTimeout);
  1001. doubleTapStartTime = null;
  1002. $element.trigger('longtap', [event.target]);
  1003. if (options.longTap) {
  1004. ret = options.longTap.call($element, event, event.target);
  1005. }
  1006. }
  1007. }
  1008. return ret;
  1009. }
  1010. //
  1011. // GESTURE VALIDATION
  1012. //
  1013. /**
  1014. * Checks the user has swipe far enough
  1015. * @return Boolean if <code>threshold</code> has been set, return true if the threshold was met, else false.
  1016. * If no threshold was set, then we return true.
  1017. * @inner
  1018. */
  1019. function validateSwipeDistance() {
  1020. var valid = true;
  1021. //If we made it past the min swipe distance..
  1022. if (options.threshold !== null) {
  1023. valid = distance >= options.threshold;
  1024. }
  1025. return valid;
  1026. }
  1027. /**
  1028. * Checks the user has swiped back to cancel.
  1029. * @return Boolean if <code>cancelThreshold</code> has been set, return true if the cancelThreshold was met, else false.
  1030. * If no cancelThreshold was set, then we return true.
  1031. * @inner
  1032. */
  1033. function didSwipeBackToCancel() {
  1034. var cancelled = false;
  1035. if (options.cancelThreshold !== null && direction !== null) {
  1036. cancelled = (getMaxDistance(direction) - distance) >= options.cancelThreshold;
  1037. }
  1038. return cancelled;
  1039. }
  1040. /**
  1041. * Checks the user has pinched far enough
  1042. * @return Boolean if <code>pinchThreshold</code> has been set, return true if the threshold was met, else false.
  1043. * If no threshold was set, then we return true.
  1044. * @inner
  1045. */
  1046. function validatePinchDistance() {
  1047. if (options.pinchThreshold !== null) {
  1048. return pinchDistance >= options.pinchThreshold;
  1049. }
  1050. return true;
  1051. }
  1052. /**
  1053. * Checks that the time taken to swipe meets the minimum / maximum requirements
  1054. * @return Boolean
  1055. * @inner
  1056. */
  1057. function validateSwipeTime() {
  1058. var result;
  1059. //If no time set, then return true
  1060. if (options.maxTimeThreshold) {
  1061. if (duration >= options.maxTimeThreshold) {
  1062. result = false;
  1063. } else {
  1064. result = true;
  1065. }
  1066. } else {
  1067. result = true;
  1068. }
  1069. return result;
  1070. }
  1071. /**
  1072. * Checks direction of the swipe and the value allowPageScroll to see if we should allow or prevent the default behaviour from occurring.
  1073. * This will essentially allow page scrolling or not when the user is swiping on a touchSwipe object.
  1074. * @param {object} jqEvent The normalised jQuery representation of the event object.
  1075. * @param {string} direction The direction of the event. See {@link $.fn.swipe.directions}
  1076. * @see $.fn.swipe.directions
  1077. * @inner
  1078. */
  1079. function validateDefaultEvent(jqEvent, direction) {
  1080. //If the option is set, allways allow the event to bubble up (let user handle weirdness)
  1081. if (options.preventDefaultEvents === false) {
  1082. return;
  1083. }
  1084. if (options.allowPageScroll === NONE) {
  1085. jqEvent.preventDefault();
  1086. } else {
  1087. var auto = options.allowPageScroll === AUTO;
  1088. switch (direction) {
  1089. case LEFT:
  1090. if ((options.swipeLeft && auto) || (!auto && options.allowPageScroll != HORIZONTAL)) {
  1091. jqEvent.preventDefault();
  1092. }
  1093. break;
  1094. case RIGHT:
  1095. if ((options.swipeRight && auto) || (!auto && options.allowPageScroll != HORIZONTAL)) {
  1096. jqEvent.preventDefault();
  1097. }
  1098. break;
  1099. case UP:
  1100. if ((options.swipeUp && auto) || (!auto && options.allowPageScroll != VERTICAL)) {
  1101. jqEvent.preventDefault();
  1102. }
  1103. break;
  1104. case DOWN:
  1105. if ((options.swipeDown && auto) || (!auto && options.allowPageScroll != VERTICAL)) {
  1106. jqEvent.preventDefault();
  1107. }
  1108. break;
  1109. case NONE:
  1110. break;
  1111. }
  1112. }
  1113. }
  1114. // PINCHES
  1115. /**
  1116. * Returns true of the current pinch meets the thresholds
  1117. * @return Boolean
  1118. * @inner
  1119. */
  1120. function validatePinch() {
  1121. var hasCorrectFingerCount = validateFingers();
  1122. var hasEndPoint = validateEndPoint();
  1123. var hasCorrectDistance = validatePinchDistance();
  1124. return hasCorrectFingerCount && hasEndPoint && hasCorrectDistance;
  1125. }
  1126. /**
  1127. * Returns true if any Pinch events have been registered
  1128. * @return Boolean
  1129. * @inner
  1130. */
  1131. function hasPinches() {
  1132. //Enure we dont return 0 or null for false values
  1133. return !!(options.pinchStatus || options.pinchIn || options.pinchOut);
  1134. }
  1135. /**
  1136. * Returns true if we are detecting pinches, and have one
  1137. * @return Boolean
  1138. * @inner
  1139. */
  1140. function didPinch() {
  1141. //Enure we dont return 0 or null for false values
  1142. return !!(validatePinch() && hasPinches());
  1143. }
  1144. // SWIPES
  1145. /**
  1146. * Returns true if the current swipe meets the thresholds
  1147. * @return Boolean
  1148. * @inner
  1149. */
  1150. function validateSwipe() {
  1151. //Check validity of swipe
  1152. var hasValidTime = validateSwipeTime();
  1153. var hasValidDistance = validateSwipeDistance();
  1154. var hasCorrectFingerCount = validateFingers();
  1155. var hasEndPoint = validateEndPoint();
  1156. var didCancel = didSwipeBackToCancel();
  1157. // if the user swiped more than the minimum length, perform the appropriate action
  1158. // hasValidDistance is null when no distance is set
  1159. var valid = !didCancel && hasEndPoint && hasCorrectFingerCount && hasValidDistance && hasValidTime;
  1160. return valid;
  1161. }
  1162. /**
  1163. * Returns true if any Swipe events have been registered
  1164. * @return Boolean
  1165. * @inner
  1166. */
  1167. function hasSwipes() {
  1168. //Enure we dont return 0 or null for false values
  1169. return !!(options.swipe || options.swipeStatus || options.swipeLeft || options.swipeRight || options.swipeUp || options.swipeDown);
  1170. }
  1171. /**
  1172. * Returns true if we are detecting swipes and have one
  1173. * @return Boolean
  1174. * @inner
  1175. */
  1176. function didSwipe() {
  1177. //Enure we dont return 0 or null for false values
  1178. return !!(validateSwipe() && hasSwipes());
  1179. }
  1180. /**
  1181. * Returns true if we have matched the number of fingers we are looking for
  1182. * @return Boolean
  1183. * @inner
  1184. */
  1185. function validateFingers() {
  1186. //The number of fingers we want were matched, or on desktop we ignore
  1187. return ((fingerCount === options.fingers || options.fingers === ALL_FINGERS) || !SUPPORTS_TOUCH);
  1188. }
  1189. /**
  1190. * Returns true if we have an end point for the swipe
  1191. * @return Boolean
  1192. * @inner
  1193. */
  1194. function validateEndPoint() {
  1195. //We have an end value for the finger
  1196. return fingerData[0].end.x !== 0;
  1197. }
  1198. // TAP / CLICK
  1199. /**
  1200. * Returns true if a click / tap events have been registered
  1201. * @return Boolean
  1202. * @inner
  1203. */
  1204. function hasTap() {
  1205. //Enure we dont return 0 or null for false values
  1206. return !!(options.tap);
  1207. }
  1208. /**
  1209. * Returns true if a double tap events have been registered
  1210. * @return Boolean
  1211. * @inner
  1212. */
  1213. function hasDoubleTap() {
  1214. //Enure we dont return 0 or null for false values
  1215. return !!(options.doubleTap);
  1216. }
  1217. /**
  1218. * Returns true if any long tap events have been registered
  1219. * @return Boolean
  1220. * @inner
  1221. */
  1222. function hasLongTap() {
  1223. //Enure we dont return 0 or null for false values
  1224. return !!(options.longTap);
  1225. }
  1226. /**
  1227. * 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.
  1228. * @return Boolean
  1229. * @inner
  1230. */
  1231. function validateDoubleTap() {
  1232. if (doubleTapStartTime == null) {
  1233. return false;
  1234. }
  1235. var now = getTimeStamp();
  1236. return (hasDoubleTap() && ((now - doubleTapStartTime) <= options.doubleTapThreshold));
  1237. }
  1238. /**
  1239. * 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.
  1240. * @return Boolean
  1241. * @inner
  1242. */
  1243. function inDoubleTap() {
  1244. return validateDoubleTap();
  1245. }
  1246. /**
  1247. * Returns true if we have a valid tap
  1248. * @return Boolean
  1249. * @inner
  1250. */
  1251. function validateTap() {
  1252. return ((fingerCount === 1 || !SUPPORTS_TOUCH) && (isNaN(distance) || distance < options.threshold));
  1253. }
  1254. /**
  1255. * Returns true if we have a valid long tap
  1256. * @return Boolean
  1257. * @inner
  1258. */
  1259. function validateLongTap() {
  1260. //slight threshold on moving finger
  1261. return ((duration > options.longTapThreshold) && (distance < DOUBLE_TAP_THRESHOLD));
  1262. }
  1263. /**
  1264. * Returns true if we are detecting taps and have one
  1265. * @return Boolean
  1266. * @inner
  1267. */
  1268. function didTap() {
  1269. //Enure we dont return 0 or null for false values
  1270. return !!(validateTap() && hasTap());
  1271. }
  1272. /**
  1273. * Returns true if we are detecting double taps and have one
  1274. * @return Boolean
  1275. * @inner
  1276. */
  1277. function didDoubleTap() {
  1278. //Enure we dont return 0 or null for false values
  1279. return !!(validateDoubleTap() && hasDoubleTap());
  1280. }
  1281. /**
  1282. * Returns true if we are detecting long taps and have one
  1283. * @return Boolean
  1284. * @inner
  1285. */
  1286. function didLongTap() {
  1287. //Enure we dont return 0 or null for false values
  1288. return !!(validateLongTap() && hasLongTap());
  1289. }
  1290. // MULTI FINGER TOUCH
  1291. /**
  1292. * Starts tracking the time between 2 finger releases, and keeps track of how many fingers we initially had up
  1293. * @inner
  1294. */
  1295. function startMultiFingerRelease(event) {
  1296. previousTouchEndTime = getTimeStamp();
  1297. fingerCountAtRelease = event.touches.length + 1;
  1298. }
  1299. /**
  1300. * Cancels the tracking of time between 2 finger releases, and resets counters
  1301. * @inner
  1302. */
  1303. function cancelMultiFingerRelease() {
  1304. previousTouchEndTime = 0;
  1305. fingerCountAtRelease = 0;
  1306. }
  1307. /**
  1308. * Checks if we are in the threshold between 2 fingers being released
  1309. * @return Boolean
  1310. * @inner
  1311. */
  1312. function inMultiFingerRelease() {
  1313. var withinThreshold = false;
  1314. if (previousTouchEndTime) {
  1315. var diff = getTimeStamp() - previousTouchEndTime
  1316. if (diff <= options.fingerReleaseThreshold) {
  1317. withinThreshold = true;
  1318. }
  1319. }
  1320. return withinThreshold;
  1321. }
  1322. /**
  1323. * gets a data flag to indicate that a touch is in progress
  1324. * @return Boolean
  1325. * @inner
  1326. */
  1327. function getTouchInProgress() {
  1328. //strict equality to ensure only true and false are returned
  1329. return !!($element.data(PLUGIN_NS + '_intouch') === true);
  1330. }
  1331. /**
  1332. * Sets a data flag to indicate that a touch is in progress
  1333. * @param {boolean} val The value to set the property to
  1334. * @inner
  1335. */
  1336. function setTouchInProgress(val) {
  1337. //If destroy is called in an event handler, we have no el, and we have already cleaned up, so return.
  1338. if(!$element) { return; }
  1339. //Add or remove event listeners depending on touch status
  1340. if (val === true) {
  1341. $element.bind(MOVE_EV, touchMove);
  1342. $element.bind(END_EV, touchEnd);
  1343. //we only have leave events on desktop, we manually calcuate leave on touch as its not supported in webkit
  1344. if (LEAVE_EV) {
  1345. $element.bind(LEAVE_EV, touchLeave);
  1346. }
  1347. } else {
  1348. $element.unbind(MOVE_EV, touchMove, false);
  1349. $element.unbind(END_EV, touchEnd, false);
  1350. //we only have leave events on desktop, we manually calcuate leave on touch as its not supported in webkit
  1351. if (LEAVE_EV) {
  1352. $element.unbind(LEAVE_EV, touchLeave, false);
  1353. }
  1354. }
  1355. //strict equality to ensure only true and false can update the value
  1356. $element.data(PLUGIN_NS + '_intouch', val === true);
  1357. }
  1358. /**
  1359. * Creates the finger data for the touch/finger in the event object.
  1360. * @param {int} id The id to store the finger data under (usually the order the fingers were pressed)
  1361. * @param {object} evt The event object containing finger data
  1362. * @return finger data object
  1363. * @inner
  1364. */
  1365. function createFingerData(id, evt) {
  1366. var f = {
  1367. start: {
  1368. x: 0,
  1369. y: 0
  1370. },
  1371. last: {
  1372. x: 0,
  1373. y: 0
  1374. },
  1375. end: {
  1376. x: 0,
  1377. y: 0
  1378. }
  1379. };
  1380. f.start.x = f.last.x = f.end.x = evt.pageX || evt.clientX;
  1381. f.start.y = f.last.y = f.end.y = evt.pageY || evt.clientY;
  1382. fingerData[id] = f;
  1383. return f;
  1384. }
  1385. /**
  1386. * Updates the finger data for a particular event object
  1387. * @param {object} evt The event object containing the touch/finger data to upadte
  1388. * @return a finger data object.
  1389. * @inner
  1390. */
  1391. function updateFingerData(evt) {
  1392. var id = evt.identifier !== undefined ? evt.identifier : 0;
  1393. var f = getFingerData(id);
  1394. if (f === null) {
  1395. f = createFingerData(id, evt);
  1396. }
  1397. f.last.x = f.end.x;
  1398. f.last.y = f.end.y;
  1399. f.end.x = evt.pageX || evt.clientX;
  1400. f.end.y = evt.pageY || evt.clientY;
  1401. return f;
  1402. }
  1403. /**
  1404. * Returns a finger data object by its event ID.
  1405. * Each touch event has an identifier property, which is used
  1406. * to track repeat touches
  1407. * @param {int} id The unique id of the finger in the sequence of touch events.
  1408. * @return a finger data object.
  1409. * @inner
  1410. */
  1411. function getFingerData(id) {
  1412. return fingerData[id] || null;
  1413. }
  1414. /**
  1415. * Sets the maximum distance swiped in the given direction.
  1416. * If the new value is lower than the current value, the max value is not changed.
  1417. * @param {string} direction The direction of the swipe
  1418. * @param {int} distance The distance of the swipe
  1419. * @inner
  1420. */
  1421. function setMaxDistance(direction, distance) {
  1422. if(direction==NONE) return;
  1423. distance = Math.max(distance, getMaxDistance(direction));
  1424. maximumsMap[direction].distance = distance;
  1425. }
  1426. /**
  1427. * gets the maximum distance swiped in the given direction.
  1428. * @param {string} direction The direction of the swipe
  1429. * @return int The distance of the swipe
  1430. * @inner
  1431. */
  1432. function getMaxDistance(direction) {
  1433. if (maximumsMap[direction]) return maximumsMap[direction].distance;
  1434. return undefined;
  1435. }
  1436. /**
  1437. * Creats a map of directions to maximum swiped values.
  1438. * @return Object A dictionary of maximum values, indexed by direction.
  1439. * @inner
  1440. */
  1441. function createMaximumsData() {
  1442. var maxData = {};
  1443. maxData[LEFT] = createMaximumVO(LEFT);
  1444. maxData[RIGHT] = createMaximumVO(RIGHT);
  1445. maxData[UP] = createMaximumVO(UP);
  1446. maxData[DOWN] = createMaximumVO(DOWN);
  1447. return maxData;
  1448. }
  1449. /**
  1450. * Creates a map maximum swiped values for a given swipe direction
  1451. * @param {string} The direction that these values will be associated with
  1452. * @return Object Maximum values
  1453. * @inner
  1454. */
  1455. function createMaximumVO(dir) {
  1456. return {
  1457. direction: dir,
  1458. distance: 0
  1459. }
  1460. }
  1461. //
  1462. // MATHS / UTILS
  1463. //
  1464. /**
  1465. * Calculate the duration of the swipe
  1466. * @return int
  1467. * @inner
  1468. */
  1469. function calculateDuration() {
  1470. return endTime - startTime;
  1471. }
  1472. /**
  1473. * Calculate the distance between 2 touches (pinch)
  1474. * @param {point} startPoint A point object containing x and y co-ordinates
  1475. * @param {point} endPoint A point object containing x and y co-ordinates
  1476. * @return int;
  1477. * @inner
  1478. */
  1479. function calculateTouchesDistance(startPoint, endPoint) {
  1480. var diffX = Math.abs(startPoint.x - endPoint.x);
  1481. var diffY = Math.abs(startPoint.y - endPoint.y);
  1482. return Math.round(Math.sqrt(diffX * diffX + diffY * diffY));
  1483. }
  1484. /**
  1485. * Calculate the zoom factor between the start and end distances
  1486. * @param {int} startDistance Distance (between 2 fingers) the user started pinching at
  1487. * @param {int} endDistance Distance (between 2 fingers) the user ended pinching at
  1488. * @return float The zoom value from 0 to 1.
  1489. * @inner
  1490. */
  1491. function calculatePinchZoom(startDistance, endDistance) {
  1492. var percent = (endDistance / startDistance) * 1;
  1493. return percent.toFixed(2);
  1494. }
  1495. /**
  1496. * Returns the pinch direction, either IN or OUT for the given points
  1497. * @return string Either {@link $.fn.swipe.directions.IN} or {@link $.fn.swipe.directions.OUT}
  1498. * @see $.fn.swipe.directions
  1499. * @inner
  1500. */
  1501. function calculatePinchDirection() {
  1502. if (pinchZoom < 1) {
  1503. return OUT;
  1504. } else {
  1505. return IN;
  1506. }
  1507. }
  1508. /**
  1509. * Calculate the length / distance of the swipe
  1510. * @param {point} startPoint A point object containing x and y co-ordinates
  1511. * @param {point} endPoint A point object containing x and y co-ordinates
  1512. * @return int
  1513. * @inner
  1514. */
  1515. function calculateDistance(startPoint, endPoint) {
  1516. return Math.round(Math.sqrt(Math.pow(endPoint.x - startPoint.x, 2) + Math.pow(endPoint.y - startPoint.y, 2)));
  1517. }
  1518. /**
  1519. * Calculate the angle of the swipe
  1520. * @param {point} startPoint A point object containing x and y co-ordinates
  1521. * @param {point} endPoint A point object containing x and y co-ordinates
  1522. * @return int
  1523. * @inner
  1524. */
  1525. function calculateAngle(startPoint, endPoint) {
  1526. var x = startPoint.x - endPoint.x;
  1527. var y = endPoint.y - startPoint.y;
  1528. var r = Math.atan2(y, x); //radians
  1529. var angle = Math.round(r * 180 / Math.PI); //degrees
  1530. //ensure value is positive
  1531. if (angle < 0) {
  1532. angle = 360 - Math.abs(angle);
  1533. }
  1534. return angle;
  1535. }
  1536. /**
  1537. * Calculate the direction of the swipe
  1538. * This will also call calculateAngle to get the latest angle of swipe
  1539. * @param {point} startPoint A point object containing x and y co-ordinates
  1540. * @param {point} endPoint A point object containing x and y co-ordinates
  1541. * @return string Either {@link $.fn.swipe.directions.LEFT} / {@link $.fn.swipe.directions.RIGHT} / {@link $.fn.swipe.directions.DOWN} / {@link $.fn.swipe.directions.UP}
  1542. * @see $.fn.swipe.directions
  1543. * @inner
  1544. */
  1545. function calculateDirection(startPoint, endPoint) {
  1546. if( comparePoints(startPoint, endPoint) ) {
  1547. return NONE;
  1548. }
  1549. var angle = calculateAngle(startPoint, endPoint);
  1550. if ((angle <= 45) && (angle >= 0)) {
  1551. return LEFT;
  1552. } else if ((angle <= 360) && (angle >= 315)) {
  1553. return LEFT;
  1554. } else if ((angle >= 135) && (angle <= 225)) {
  1555. return RIGHT;
  1556. } else if ((angle > 45) && (angle < 135)) {
  1557. return DOWN;
  1558. } else {
  1559. return UP;
  1560. }
  1561. }
  1562. /**
  1563. * Returns a MS time stamp of the current time
  1564. * @return int
  1565. * @inner
  1566. */
  1567. function getTimeStamp() {
  1568. var now = new Date();
  1569. return now.getTime();
  1570. }
  1571. /**
  1572. * Returns a bounds object with left, right, top and bottom properties for the element specified.
  1573. * @param {DomNode} The DOM node to get the bounds for.
  1574. */
  1575. function getbounds(el) {
  1576. el = $(el);
  1577. var offset = el.offset();
  1578. var bounds = {
  1579. left: offset.left,
  1580. right: offset.left + el.outerWidth(),
  1581. top: offset.top,
  1582. bottom: offset.top + el.outerHeight()
  1583. }
  1584. return bounds;
  1585. }
  1586. /**
  1587. * Checks if the point object is in the bounds object.
  1588. * @param {object} point A point object.
  1589. * @param {int} point.x The x value of the point.
  1590. * @param {int} point.y The x value of the point.
  1591. * @param {object} bounds The bounds object to test
  1592. * @param {int} bounds.left The leftmost value
  1593. * @param {int} bounds.right The righttmost value
  1594. * @param {int} bounds.top The topmost value
  1595. * @param {int} bounds.bottom The bottommost value
  1596. */
  1597. function isInBounds(point, bounds) {
  1598. return (point.x > bounds.left && point.x < bounds.right && point.y > bounds.top && point.y < bounds.bottom);
  1599. };
  1600. /**
  1601. * Checks if the two points are equal
  1602. * @param {object} point A point object.
  1603. * @param {object} point B point object.
  1604. * @return true of the points match
  1605. */
  1606. function comparePoints(pointA, pointB) {
  1607. return (pointA.x == pointB.x && pointA.y == pointB.y);
  1608. }
  1609. }
  1610. /**
  1611. * A catch all handler that is triggered for all swipe directions.
  1612. * @name $.fn.swipe#swipe
  1613. * @event
  1614. * @default null
  1615. * @param {EventObject} event The original event object
  1616. * @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
  1617. * @param {int} distance The distance the user swiped
  1618. * @param {int} duration The duration of the swipe in milliseconds
  1619. * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
  1620. * @param {object} fingerData The coordinates of fingers in event
  1621. * @param {string} currentDirection The current direction the user is swiping.
  1622. */
  1623. /**
  1624. * A handler that is triggered for "left" swipes.
  1625. * @name $.fn.swipe#swipeLeft
  1626. * @event
  1627. * @default null
  1628. * @param {EventObject} event The original event object
  1629. * @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
  1630. * @param {int} distance The distance the user swiped
  1631. * @param {int} duration The duration of the swipe in milliseconds
  1632. * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
  1633. * @param {object} fingerData The coordinates of fingers in event
  1634. * @param {string} currentDirection The current direction the user is swiping.
  1635. */
  1636. /**
  1637. * A handler that is triggered for "right" swipes.
  1638. * @name $.fn.swipe#swipeRight
  1639. * @event
  1640. * @default null
  1641. * @param {EventObject} event The original event object
  1642. * @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
  1643. * @param {int} distance The distance the user swiped
  1644. * @param {int} duration The duration of the swipe in milliseconds
  1645. * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
  1646. * @param {object} fingerData The coordinates of fingers in event
  1647. * @param {string} currentDirection The current direction the user is swiping.
  1648. */
  1649. /**
  1650. * A handler that is triggered for "up" swipes.
  1651. * @name $.fn.swipe#swipeUp
  1652. * @event
  1653. * @default null
  1654. * @param {EventObject} event The original event object
  1655. * @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
  1656. * @param {int} distance The distance the user swiped
  1657. * @param {int} duration The duration of the swipe in milliseconds
  1658. * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
  1659. * @param {object} fingerData The coordinates of fingers in event
  1660. * @param {string} currentDirection The current direction the user is swiping.
  1661. */
  1662. /**
  1663. * A handler that is triggered for "down" swipes.
  1664. * @name $.fn.swipe#swipeDown
  1665. * @event
  1666. * @default null
  1667. * @param {EventObject} event The original event object
  1668. * @param {int} direction The direction the user swiped in. See {@link $.fn.swipe.directions}
  1669. * @param {int} distance The distance the user swiped
  1670. * @param {int} duration The duration of the swipe in milliseconds
  1671. * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
  1672. * @param {object} fingerData The coordinates of fingers in event
  1673. * @param {string} currentDirection The current direction the user is swiping.
  1674. */
  1675. /**
  1676. * A handler triggered for every phase of the swipe. This handler is constantly fired for the duration of the pinch.
  1677. * This is triggered regardless of swipe thresholds.
  1678. * @name $.fn.swipe#swipeStatus
  1679. * @event
  1680. * @default null
  1681. * @param {EventObject} event The original event object
  1682. * @param {string} phase The phase of the swipe event. See {@link $.fn.swipe.phases}
  1683. * @param {string} direction The direction the user swiped in. This is null if the user has yet to move. See {@link $.fn.swipe.directions}
  1684. * @param {int} distance The distance the user swiped. This is 0 if the user has yet to move.
  1685. * @param {int} duration The duration of the swipe in milliseconds
  1686. * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
  1687. * @param {object} fingerData The coordinates of fingers in event
  1688. * @param {string} currentDirection The current direction the user is swiping.
  1689. */
  1690. /**
  1691. * A handler triggered for pinch in events.
  1692. * @name $.fn.swipe#pinchIn
  1693. * @event
  1694. * @default null
  1695. * @param {EventObject} event The original event object
  1696. * @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions}
  1697. * @param {int} distance The distance the user pinched
  1698. * @param {int} duration The duration of the swipe in milliseconds
  1699. * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
  1700. * @param {int} zoom The zoom/scale level the user pinched too, 0-1.
  1701. * @param {object} fingerData The coordinates of fingers in event
  1702. */
  1703. /**
  1704. * A handler triggered for pinch out events.
  1705. * @name $.fn.swipe#pinchOut
  1706. * @event
  1707. * @default null
  1708. * @param {EventObject} event The original event object
  1709. * @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions}
  1710. * @param {int} distance The distance the user pinched
  1711. * @param {int} duration The duration of the swipe in milliseconds
  1712. * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
  1713. * @param {int} zoom The zoom/scale level the user pinched too, 0-1.
  1714. * @param {object} fingerData The coordinates of fingers in event
  1715. */
  1716. /**
  1717. * A handler triggered for all pinch events. This handler is constantly fired for the duration of the pinch. This is triggered regardless of thresholds.
  1718. * @name $.fn.swipe#pinchStatus
  1719. * @event
  1720. * @default null
  1721. * @param {EventObject} event The original event object
  1722. * @param {int} direction The direction the user pinched in. See {@link $.fn.swipe.directions}
  1723. * @param {int} distance The distance the user pinched
  1724. * @param {int} duration The duration of the swipe in milliseconds
  1725. * @param {int} fingerCount The number of fingers used. See {@link $.fn.swipe.fingers}
  1726. * @param {int} zoom The zoom/scale level the user pinched too, 0-1.
  1727. * @param {object} fingerData The coordinates of fingers in event
  1728. */
  1729. /**
  1730. * A click handler triggered when a user simply clicks, rather than swipes on an element.
  1731. * This is deprecated since version 1.6.2, any assignment to click will be assigned to the tap handler.
  1732. * You cannot use <code>on</code> to bind to this event as the default jQ <code>click</code> event will be triggered.
  1733. * Use the <code>tap</code> event instead.
  1734. * @name $.fn.swipe#click
  1735. * @event
  1736. * @deprecated since version 1.6.2, please use {@link $.fn.swipe#tap} instead
  1737. * @default null
  1738. * @param {EventObject} event The original event object
  1739. * @param {DomObject} target The element clicked on.
  1740. */
  1741. /**
  1742. * A click / tap handler triggered when a user simply clicks or taps, rather than swipes on an element.
  1743. * @name $.fn.swipe#tap
  1744. * @event
  1745. * @default null
  1746. * @param {EventObject} event The original event object
  1747. * @param {DomObject} target The element clicked on.
  1748. */
  1749. /**
  1750. * A double tap handler triggered when a user double clicks or taps on an element.
  1751. * You can set the time delay for a double tap with the {@link $.fn.swipe.defaults#doubleTapThreshold} property.
  1752. * Note: If you set both <code>doubleTap</code> and <code>tap</code> handlers, the <code>tap</code> event will be delayed by the <code>doubleTapThreshold</code>
  1753. * as the script needs to check if its a double tap.
  1754. * @name $.fn.swipe#doubleTap
  1755. * @see $.fn.swipe.defaults#doubleTapThreshold
  1756. * @event
  1757. * @default null
  1758. * @param {EventObject} event The original event object
  1759. * @param {DomObject} target The element clicked on.
  1760. */
  1761. /**
  1762. * A long tap handler triggered once a tap has been release if the tap was longer than the longTapThreshold.
  1763. * You can set the time delay for a long tap with the {@link $.fn.swipe.defaults#longTapThreshold} property.
  1764. * @name $.fn.swipe#longTap
  1765. * @see $.fn.swipe.defaults#longTapThreshold
  1766. * @event
  1767. * @default null
  1768. * @param {EventObject} event The original event object
  1769. * @param {DomObject} target The element clicked on.
  1770. */
  1771. /**
  1772. * A hold tap handler triggered as soon as the longTapThreshold is reached
  1773. * You can set the time delay for a long tap with the {@link $.fn.swipe.defaults#longTapThreshold} property.
  1774. * @name $.fn.swipe#hold
  1775. * @see $.fn.swipe.defaults#longTapThreshold
  1776. * @event
  1777. * @default null
  1778. * @param {EventObject} event The original event object
  1779. * @param {DomObject} target The element clicked on.
  1780. */
  1781. }));