-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathonSwipe.js
More file actions
executable file
·67 lines (52 loc) · 1.81 KB
/
onSwipe.js
File metadata and controls
executable file
·67 lines (52 loc) · 1.81 KB
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
function onSwipe(elem, options) {
options = options || {};
let startX,
startY,
dist,
onRight = options.onRight || function() {},
onLeft = options.onLeft || function(){},
tolerance = options.tolerance || 50, // maximum vertical distance
threshold = options.threshold || 150, //required min distance traveled to be considered swipe
allowedTime = options.allowedTime || 500, // maximum time allowed to travel that distance
elapsedTime,
startTime;
elem.addEventListener('touchstart', function(e) {
let touchobj = e.changedTouches[0];
dist = 0;
startX = touchobj.pageX;
startY = touchobj.pageY;
//console.log("start", startX, startY);
startTime = Date.now(); // record time when finger first makes contact with surface
});
elem.addEventListener('touchend', function(e) {
let touchobj = e.changedTouches[0];
dist = touchobj.pageX - startX; // get total dist traveled by finger while in contact with surface
elapsedTime = Date.now() - startTime; // get time elapsed
//console.log("end", touchobj.pageX, touchobj.pageY);
// too much up/down
if (Math.abs(touchobj.pageY - startY) > tolerance) return;
//console.log("time", elapsedTime, allowedTime);
// too slow
if (elapsedTime > allowedTime) return;
let insideScrollable = false;
let elem = e.target;
while(elem != document.body) {
if (elem.scrollWidth > elem.clientWidth) {
insideScrollable = true;
break;
}
elem = elem.parentElement;
}
if (insideScrollable) return;
//console.log("threshold", dist, threshold);
if (dist > threshold) {
//console.log("right");
onRight(e);
}
if (dist < -threshold) {
//console.log("left");
onLeft(e);
}
});
}
module.exports = onSwipe;