-
Notifications
You must be signed in to change notification settings - Fork 0
/
swipey.js
84 lines (66 loc) · 2.67 KB
/
swipey.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
const swipey = {
points: {
x: {
start: 0,
end: 0
},
y: {
start: 0,
end: 0
}
},
add: function(swipeElement, callback, options){
let defaultOptions = {
diagonal: true,
horizontal: true,
vertical: true,
swipeDistance: 100
};
options = Object.assign(defaultOptions, options);
swipeElement.addEventListener('touchstart', function(ev) {
swipey.points.x.start = ev.changedTouches[0].clientX;
swipey.points.y.start = ev.changedTouches[0].clientY;
}, false);
swipeElement.addEventListener('touchend', function(ev) {
swipey.points.x.end = ev.changedTouches[0].clientX;
swipey.points.y.end = ev.changedTouches[0].clientY;
swipey.calculateSwipes(swipeElement, callback, options);
}, false);
swipeElement.addEventListener('mousedown', function(ev) {
swipey.points.x.start = ev.clientX;
swipey.points.y.start = ev.clientY;
}, false);
swipeElement.addEventListener('mouseup', function(ev) {
swipey.points.x.end = ev.clientX;
swipey.points.y.end = ev.clientY;
swipey.calculateSwipes(swipeElement, callback, options);
}, false);
},
calculateSwipes: function(swipeElement, callback, options){
let xDiff = swipey.points.x.start - swipey.points.x.end;
let yDiff = swipey.points.y.start - swipey.points.y.end;
if (Math.abs(xDiff) > options.swipeDistance || Math.abs(yDiff) > options.swipeDistance){
if (options.diagonal && Math.abs(xDiff) > options.swipeDistance && Math.abs(yDiff) > options.swipeDistance){
callback({
swipeLength: Math.sqrt(Math.pow(xDiff, 2) + Math.pow(yDiff, 2)),
direction: (yDiff > 0 ? "up" : "down") + "-" + (xDiff > 0 ? "left" : "right"),
target: swipeElement
});
}
else if (options.horizontal && Math.abs(xDiff) > options.swipeDistance){
callback({
swipeLength: Math.abs(xDiff),
direction: xDiff > 0 ? "left" : "right",
target: swipeElement
});
}
else if (options.vertical && Math.abs(yDiff) > options.swipeDistance){
callback({
swipeLength: Math.abs(yDiff),
direction: yDiff > 0 ? "up" : "down",
target: swipeElement
});
}
}
}
};