I have a swipe detection function detectswipe(el, func)
that listens for data-animate="swipe"
and runs the function swipe(el, d)
when swiped on mobile. The problem is it only runs on the first instance of data-animate="swipe"
and not every instance.
How do I change my code to run on every instance of data-animate="swipe"
?
JavaScript
x
69
69
1
function detectswipe(el, func) {
2
swipe_det = new Object();
3
swipe_det.sX = 0;
4
swipe_det.sY = 0;
5
swipe_det.eX = 0;
6
swipe_det.eY = 0;
7
var min_x = 30; //min x swipe for horizontal swipe
8
var max_x = 30; //max x difference for vertical swipe
9
var min_y = 50; //min y swipe for vertical swipe
10
var max_y = 60; //max y difference for horizontal swipe
11
var direc = "";
12
ele = document.querySelector(el);
13
ele.addEventListener(
14
"touchstart",
15
function (e) {
16
var t = e.touches[0];
17
swipe_det.sX = t.screenX;
18
swipe_det.sY = t.screenY;
19
},
20
false
21
);
22
ele.addEventListener(
23
"touchmove",
24
function (e) {
25
e.preventDefault();
26
var t = e.touches[0];
27
swipe_det.eX = t.screenX;
28
swipe_det.eY = t.screenY;
29
},
30
false
31
);
32
ele.addEventListener(
33
"touchend",
34
function (e) {
35
//horizontal detection
36
if (
37
(swipe_det.eX - min_x > swipe_det.sX ||
38
swipe_det.eX + min_x < swipe_det.sX) &&
39
swipe_det.eY < swipe_det.sY + max_y &&
40
swipe_det.sY > swipe_det.eY - max_y
41
) {
42
if (swipe_det.eX > swipe_det.sX) direc = "r";
43
else direc = "l";
44
}
45
//vertical detection
46
if (
47
(swipe_det.eY - min_y > swipe_det.sY ||
48
swipe_det.eY + min_y < swipe_det.sY) &&
49
swipe_det.eX < swipe_det.sX + max_x &&
50
swipe_det.sX > swipe_det.eX - max_x
51
) {
52
if (swipe_det.eY > swipe_det.sY) direc = "d";
53
else direc = "u";
54
}
55
56
if (direc != "") {
57
if (typeof func == "function") func(el, direc);
58
}
59
direc = "";
60
},
61
false
62
);
63
}
64
65
function swipe(el, d) {
66
$(el).addClass("active");
67
}
68
69
detectswipe("[data-animate='swipe']", swipe);
JavaScript
1
12
12
1
body {
2
display: flex
3
}
4
.item {
5
margin: 2.3rem;
6
height: 100px;
7
width: 100px;
8
background: orange
9
}
10
.item.active {
11
background: green
12
}
JavaScript
1
3
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<div class="item" data-animate="swipe"></div>
3
<div class="item" data-animate="swipe"></div>
Advertisement
Answer
To boil it down to the basics:
JavaScript
1
14
14
1
function detectswipe(el, func) {
2
/*Your stuff here*/
3
4
/*Get all the elements*/
5
ele = document.querySelectorAll(el);
6
/*Iterate the elements*/
7
ele.forEach(function(item){
8
/*Add the event listeners*/
9
item.addEventListener("touchstart", function(e){/*your stuff*/});
10
item.addEventListener("touchmove", function(e){/*your stuff*/});
11
/*etc*/
12
});
13
}
14
Event delegation could also work here but we don’t know much about the structure of your document.