-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswipe-detection.js
261 lines (227 loc) · 8.69 KB
/
swipe-detection.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
/**
*
* Version: 2.0.4
* Author: Gianluca Guarini
* Contact: [email protected]
* Website: http://www.gianlucaguarini.com/
* Twitter: @gianlucaguarini
*
* Copyright (c) Gianluca Guarini
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**/
/* global jQuery */
(function(doc, win) {
if (typeof doc.createEvent !== 'function') return false // no tap events here
// helpers
var pointerEvent = function(type) {
var lo = type.toLowerCase(),
ms = 'MS' + type
return navigator.msPointerEnabled ? ms : window.PointerEvent ? lo : false
},
touchEvent = function(name) {
return 'on' + name in window ? name : false
},
defaults = {
useJquery: !win.IGNORE_JQUERY && typeof jQuery !== 'undefined',
swipeThreshold: win.SWIPE_THRESHOLD || 100,
tapThreshold: win.TAP_THRESHOLD || 150, // range of time where a tap event could be detected
dbltapThreshold: win.DBL_TAP_THRESHOLD || 200, // delay needed to detect a double tap
longtapThreshold: win.LONG_TAP_THRESHOLD || 1000, // delay needed to detect a long tap
tapPrecision: win.TAP_PRECISION / 2 || 60 / 2, // touch events boundaries ( 60px by default )
justTouchEvents: win.JUST_ON_TOUCH_DEVICES
},
// was initially triggered a "touchstart" event?
wasTouch = false,
touchevents = {
touchstart: touchEvent('touchstart') || pointerEvent('PointerDown'),
touchend: touchEvent('touchend') || pointerEvent('PointerUp'),
touchmove: touchEvent('touchmove') || pointerEvent('PointerMove')
},
isTheSameFingerId = function(e) {
return !e.pointerId || typeof pointerId === 'undefined' || e.pointerId === pointerId
},
setListener = function(elm, events, callback) {
var eventsArray = events.split(' '),
i = eventsArray.length
while (i--) {
elm.addEventListener(eventsArray[i], callback, false)
}
},
getPointerEvent = function(event) {
return event.targetTouches ? event.targetTouches[0] : event
},
isMultipleTouches = function(event) {
return event.targetTouches && event.targetTouches.length > 1
},
getTimestamp = function () {
return new Date().getTime()
},
sendEvent = function(elm, eventName, originalEvent, data) {
var customEvent = doc.createEvent('Event')
customEvent.originalEvent = originalEvent
data = data || {}
data.x = currX
data.y = currY
data.distance = data.distance
// jquery
if (defaults.useJquery) {
customEvent = jQuery.Event(eventName, {originalEvent: originalEvent})
jQuery(elm).trigger(customEvent, data)
}
// addEventListener
if (customEvent.initEvent) {
for (var key in data) {
customEvent[key] = data[key]
}
customEvent.initEvent(eventName, true, true)
elm.dispatchEvent(customEvent)
}
// detect all the inline events
// also on the parent nodes
while (elm) {
// inline
if (elm['on' + eventName])
elm['on' + eventName](customEvent)
elm = elm.parentNode
}
},
onTouchStart = function(e) {
/**
* Skip all the mouse events
* events order:
* Chrome:
* touchstart
* touchmove
* touchend
* mousedown
* mousemove
* mouseup <- this must come always after a "touchstart"
*
* Safari
* touchstart
* mousedown
* touchmove
* mousemove
* touchend
* mouseup <- this must come always after a "touchstart"
*/
if (!isTheSameFingerId(e) || isMultipleTouches(e)) return
pointerId = e.pointerId
// it looks like it was a touch event!
if (e.type !== 'mousedown')
wasTouch = true
// skip this event we don't need to track it now
if (e.type === 'mousedown' && wasTouch) return
var pointer = getPointerEvent(e)
// caching the current x
cachedX = currX = pointer.pageX
// caching the current y
cachedY = currY = pointer.pageY
longtapTimer = setTimeout(function() {
sendEvent(e.target, 'longtap', e)
target = e.target
}, defaults.longtapThreshold)
// we will use these variables on the touchend events
timestamp = getTimestamp()
tapNum++
},
onTouchEnd = function(e) {
if (!isTheSameFingerId(e) || isMultipleTouches(e)) return
pointerId = undefined
// skip the mouse events if previously a touch event was dispatched
// and reset the touch flag
if (e.type === 'mouseup' && wasTouch) {
wasTouch = false
return
}
var eventsArr = [],
now = getTimestamp(),
deltaY = cachedY - currY,
deltaX = cachedX - currX
// clear the previous timer if it was set
clearTimeout(dblTapTimer)
// kill the long tap timer
clearTimeout(longtapTimer)
if (deltaX <= -defaults.swipeThreshold)
eventsArr.push('swiperight')
if (deltaX >= defaults.swipeThreshold)
eventsArr.push('swipeleft')
if (deltaY <= -defaults.swipeThreshold)
eventsArr.push('swipedown')
if (deltaY >= defaults.swipeThreshold)
eventsArr.push('swipeup')
if (eventsArr.length) {
for (var i = 0; i < eventsArr.length; i++) {
var eventName = eventsArr[i]
sendEvent(e.target, eventName, e, {
distance: {
x: Math.abs(deltaX),
y: Math.abs(deltaY)
}
})
}
// reset the tap counter
tapNum = 0
} else {
if (
cachedX >= currX - defaults.tapPrecision &&
cachedX <= currX + defaults.tapPrecision &&
cachedY >= currY - defaults.tapPrecision &&
cachedY <= currY + defaults.tapPrecision
) {
if (timestamp + defaults.tapThreshold - now >= 0)
{
// Here you get the Tap event
sendEvent(e.target, tapNum >= 2 && target === e.target ? 'dbltap' : 'tap', e)
target= e.target
}
}
// reset the tap counter
dblTapTimer = setTimeout(function() {
tapNum = 0
}, defaults.dbltapThreshold)
}
},
onTouchMove = function(e) {
if (!isTheSameFingerId(e)) return
// skip the mouse move events if the touch events were previously detected
if (e.type === 'mousemove' && wasTouch) return
var pointer = getPointerEvent(e)
currX = pointer.pageX
currY = pointer.pageY
},
tapNum = 0,
pointerId, currX, currY, cachedX, cachedY, timestamp, target, dblTapTimer, longtapTimer
//setting the events listeners
// we need to debounce the callbacks because some devices multiple events are triggered at same time
setListener(doc, touchevents.touchstart + (defaults.justTouchEvents ? '' : ' mousedown'), onTouchStart)
setListener(doc, touchevents.touchend + (defaults.justTouchEvents ? '' : ' mouseup'), onTouchEnd)
setListener(doc, touchevents.touchmove + (defaults.justTouchEvents ? '' : ' mousemove'), onTouchMove)
// Configure the tocca default options at any time
win.tocca = function(options) {
for (var opt in options) {
defaults[opt] = options[opt]
}
return defaults
}
})(document, window)