How can you detect that a user swiped his finger in some direction over a web page with JavaScript?
I was wondering if there was one solution that would work for websites on both the iPhone and an Android phone.
Advertisement
Answer
Simple vanilla JS code sample:
JavaScript
x
46
46
1
document.addEventListener('touchstart', handleTouchStart, false);
2
document.addEventListener('touchmove', handleTouchMove, false);
3
4
var xDown = null;
5
var yDown = null;
6
7
function getTouches(evt) {
8
return evt.touches || // browser API
9
evt.originalEvent.touches; // jQuery
10
}
11
12
function handleTouchStart(evt) {
13
const firstTouch = getTouches(evt)[0];
14
xDown = firstTouch.clientX;
15
yDown = firstTouch.clientY;
16
};
17
18
function handleTouchMove(evt) {
19
if ( ! xDown || ! yDown ) {
20
return;
21
}
22
23
var xUp = evt.touches[0].clientX;
24
var yUp = evt.touches[0].clientY;
25
26
var xDiff = xDown - xUp;
27
var yDiff = yDown - yUp;
28
29
if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
30
if ( xDiff > 0 ) {
31
/* right swipe */
32
} else {
33
/* left swipe */
34
}
35
} else {
36
if ( yDiff > 0 ) {
37
/* down swipe */
38
} else {
39
/* up swipe */
40
}
41
}
42
/* reset values */
43
xDown = null;
44
yDown = null;
45
};
46
Tested in Android.