-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
76 lines (62 loc) · 2.01 KB
/
index.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
module.exports = function createTapListener(el, callback, useCapture) {
var startX = 0;
var startY = 0;
var touchStarted = false;
var touchMoved = false;
// Assume that if a touchstart event initiates, the user is
// using touch and click events should be ignored.
// If this isn't done, touch-clicks will fire the callback
// twice: once on touchend, once on the subsequent "click".
var usingTouch = false;
el.addEventListener('click', handleClick, useCapture);
el.addEventListener('touchstart', handleTouchstart, useCapture);
function handleClick(e) {
if (usingTouch) return;
callback(e);
}
function handleTouchstart(e) {
usingTouch = true;
if (touchStarted) return;
touchStarted = true;
el.addEventListener('touchmove', handleTouchmove, useCapture);
el.addEventListener('touchend', handleTouchend, useCapture);
el.addEventListener('touchcancel', handleTouchcancel, useCapture);
touchMoved = false;
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
}
function handleTouchmove(e) {
if (touchMoved) return;
if (
Math.abs(e.touches[0].clientX - startX) <= 10
&& Math.abs(e.touches[0].clientY - startY) <= 10
) return;
touchMoved = true;
}
function handleTouchend(e) {
touchStarted = false;
removeSecondaryTouchListeners();
if (!touchMoved) {
callback(e);
}
}
function handleTouchcancel() {
touchStarted = false;
touchMoved = false;
startX = 0;
startY = 0;
}
function removeSecondaryTouchListeners() {
el.removeEventListener('touchmove', handleTouchmove, useCapture);
el.removeEventListener('touchend', handleTouchend, useCapture);
el.removeEventListener('touchcancel', handleTouchcancel, useCapture);
}
function removeTapListener() {
el.removeEventListener('click', handleClick, useCapture);
el.removeEventListener('touchstart', handleTouchstart, useCapture);
removeSecondaryTouchListeners();
}
return {
remove: removeTapListener,
};
};