Swipe gestures are a common way for users to interact with touch-enabled mobile devices. Detecting swipe gestures in JavaScript can allow for more intuitive and responsive user interfaces on your websites and web applications.
In this article, we will explore how to detect swipe gestures in JavaScript using the javascript touch events API. We will cover the following topics with examples:
- Basic touch events for swiping
- Detecting swipe gestures
- Handling multiple touch points
Basic touch events
Before we dive into detecting swipe gestures, it’s important to understand the basics of touch swipe events in JavaScript. Touch events are a set of browser events that are fired when a user interacts with a touch-enabled device. The touch events API provides several events that can be used to handle touch interactions, including:
- touchstart: Fired when a finger is placed on the screen.
- touchmove: Fired when a finger is moved across the screen.
- touchend: Fired when a finger is lifted off the screen.
- touchcancel: Fired when a touch event is cancelled.
Each touch event provides information about the touch point(s) involved in the interaction, including the position of the touch point on the screen and the time of the event.
Detecting Swipe Gestures
To detect swipe gestures, we can use the touchstart, touchmove and touchend events. The basic idea is to track the position of the touch point during the touch interaction and then determine if the touch interaction was a swipe based on the distance and direction of the touch movement.
Here’s an example of how to detect a swipe gestures in HTML and JavaScript:
Firstly, we have created a simple HTML file including an element with the its id to perform detection of swipe gestures
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Detect Swipe Gesrures</title>
</head>
<body>
<div
id="element"
style="width: 300px; height: 300px; background-color: royalblue"
></div>
</body>
</html>
Then, we built the JavaScript side to perform detection of swipe gestures based on the swipe’s duration and distance.
const element = document.getElementById("element");
let startX;
let startY;
let distX;
let distY;
let threshold = 150; // minimum distance required for a swipe gesture
let restraint = 100; // maximum distance allowed for vertical movement
let allowedTime = 300; // maximum time allowed for a swipe gesture
element.addEventListener("touchstart", function (event) {
startX = event.touches[0].pageX;
startY = event.touches[0].pageY;
startTime = new Date().getTime();
distX = 0;
distY = 0;
});
element.addEventListener("touchmove", function (event) {
if (event.touches.length > 1) {
return; // ignore multi-touch gestures
}
distX = event.touches[0].pageX - startX;
distY = event.touches[0].pageY - startY;
});
element.addEventListener("touchend", function (event) {
let elapsedTime = new Date().getTime() - startTime;
if (elapsedTime <= allowedTime) {
if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint) {
if (distX > 0) {
console.log("Swipe Right");
// swipe right
} else {
console.log("Swipe Left");
// swipe left
}
} else if (
Math.abs(distY) >= threshold &&
Math.abs(distX) <= restraint
) {
if (distY < 0) {
console.log("Swipe Up");
// swipe up
} else {
console.log("Swipe Down");
// swipe down
}
}
}
});
The let statements create variables for the starting X and Y coordinates of the touch, the X and Y distance travelled during the swipe and the minimum distance required for a swipe gesture, maximum distance allowed for vertical movement and maximum time allowed for a swipe gesture.
The element.addEventListener(“touchstart”, function (event) {…}); adds an event listener to detect when the user first touches the screen. This records the starting X and Y coordinates of the touch, the time the touch occurred and resets the distance travelled during the swipe.
The element.addEventListener(“touchmove”, function (event) {…}); adds an event listener to detect when the user’s finger moves on the screen. This calculates the X and Y distance travelled during the swipe, but only if there is only one finger on the screen.
The element.addEventListener(“touchend”, function (event) {…}); adds an event listener to detect when the user lifts their finger off the screen. This calculates the total time taken to complete the swipe gesture, and checks whether the distance and time travelled meet the minimum requirements for a swipe gesture.
Handling Multiple Touch Points
It’s important to note that the code above only handles a single touch point. To handle multiple touch points (i.e. gestures involving more than one finger), we would need to modify the code to track each touch point separately and then determine if the touch interaction was a gesture involving multiple touch points.
Here’s an example of how to handle multiple touch points:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Detect Swipe Gesrures</title>
</head>
<body>
<div
id="element"
style="width: 300px; height: 300px; background-color: royalblue"
></div>
</body>
<script>
const element = document.getElementById("element");
let touchPositions = [];
element.addEventListener("touchstart", (event) => {
event.preventDefault();
for (let i = 0; i < event.touches.length; i++) {
let touch = event.touches[i];
touchPositions[touch.identifier] = {
x: touch.pageX,
y: touch.pageY,
};
console.log(touchPositions);
}
});
element.addEventListener("touchmove", (event) => {
event.preventDefault();
for (let i = 0; i < event.touches.length; i++) {
let touch = event.touches[i];
let touchPosition = touchPositions[touch.identifier];
if (touchPosition) {
let deltaX = touch.pageX - touchPosition.x;
let deltaY = touch.pageY - touchPosition.y;
// Compute the distance and direction of the swipe
// ...
touchPositions[touch.identifier] = {
x: touch.pageX,
y: touch.pageY,
};
}
}
});
element.addEventListener("touchend", (event) => {
event.preventDefault();
for (let i = 0; i < event.changedTouches.length; i++) {
let touch = event.changedTouches[i];
delete touchPositions[touch.identifier];
}
});
</script>
</html>
When a touchstart event is triggered, the code first prevents the default behavior of the event using the preventDefault method. It then loops through all the touches in the event object and stores the position of each touch in the touchPositions array using the touch’s unique identifier as the key.
When a touchmove event is triggered, the code first prevents the default behavior of the event using the preventDefault method. It then loops through all the touches in the event object and calculates the distance and direction of the swipe for each touch based on the touch’s current position and the position stored in the touchPositions array. It updates the position of each touch in the touchPositions array.
When a touchend event is triggered, the code first prevents the default behavior of the event using the preventDefault method. It then loops through all the changedTouches in the event object and removes the corresponding touch from the touchPositions array using the touch’s unique identifier as the key since touching is finished.
Overall, this code allows for the tracking and handling of touch events on a specific HTML element by storing and updating the positions of each touch in an array. It can be used for various touch-related functionalities such as swiping, scrolling or pinch zooming, among others.
Conclusion
Detecting swipe gestures in JavaScript can add a lot of interactivity to your web pages or web applications. By using the touch events provided by browsers, you can easily detect horizontal and vertical swipe gestures, and trigger custom actions based on these gestures.
In this article, we’ve looked at how to detect swipe gestures using JavaScript, as well as detecting multiple touches. We’ve provided example code that you can use to get started. However, this is just the beginning – there are many other types of touch gestures that you can detect, such as pinch and rotate gestures, which you can use to create even more advanced interactivity in your web applications.
Thank you for reading.