I want to make simple game in js. But for that I want to user play by swiping finger/cursor on the screen, up / down / right / left. There is a simple way to make that?
Asked
Active
Viewed 1.9k times
5
-
You could consider a library such as [HammerJS](https://hammerjs.github.io/) – Alexander Staroselsky Nov 07 '18 at 15:22
1 Answers
27
You can try this. Very simple and easy to understand.
var container = document.querySelector("CLASS OR ID FOR WHERE YOU WANT TO DETECT SWIPE");
container.addEventListener("touchstart", startTouch, false);
container.addEventListener("touchmove", moveTouch, false);
// Swipe Up / Down / Left / Right
var initialX = null;
var initialY = null;
function startTouch(e) {
initialX = e.touches[0].clientX;
initialY = e.touches[0].clientY;
};
function moveTouch(e) {
if (initialX === null) {
return;
}
if (initialY === null) {
return;
}
var currentX = e.touches[0].clientX;
var currentY = e.touches[0].clientY;
var diffX = initialX - currentX;
var diffY = initialY - currentY;
if (Math.abs(diffX) > Math.abs(diffY)) {
// sliding horizontally
if (diffX > 0) {
// swiped left
console.log("swiped left");
} else {
// swiped right
console.log("swiped right");
}
} else {
// sliding vertically
if (diffY > 0) {
// swiped up
console.log("swiped up");
} else {
// swiped down
console.log("swiped down");
}
}
initialX = null;
initialY = null;
e.preventDefault();
};
Reference: https://www.kirupa.com/html5/detecting_touch_swipe_gestures.htm

Mahbub Hasan
- 441
- 5
- 5
-
1While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Luca Kiebel Nov 07 '18 at 15:27
-
-
2
-
-
It is better to set up 3 event listeners : ` container.addEventListener("touchend", endTouch, false);` ` var initialX = null;` ` var initialY = null;` ` var currentX = null;` ` var currentY = null;` ` function startTouch(e) {` ` (unchanged)` ` };` ` function moveTouch(e) {` ` currentX = e.touches[0].clientX;` ` currentY = e.touches[0].clientY;` ` }` ` function endTouch(e) {` ` if (initialX === null || initialY===null) {` ` return;` ` }` ` var diffX = initialX - currentX;` ` var diffY = initialY - currentY;` ` if (Math.abs(diffX) > ...` – eosphere Nov 28 '22 at 14:06
-
-
@Piotr : In fact, after reading the other thread "Detect a finger swipe through JavaScript on the iPhone and Android", the solution proposed is more elegant than this one. – eosphere Dec 01 '22 at 11:05
-
@eosphere Ah, ok I found it: https://stackoverflow.com/questions/2264072/detect-a-finger-swipe-through-javascript-on-the-iphone-and-android it is a lot of read and not too many answers use touchEnd, but anyway thanks for sharing! – Piotr Śródka Dec 18 '22 at 07:58