jquery.touchSwipe.js 72 KB

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