jquery.touchSwipe.js 77 KB

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