About
The difference between a swipe/drag and a click is the distance traveled by the mouse.
To make the difference between a swipe and a click event:
- we locate the mouse at the mousedown event
- we locate the mouse at the mouseup event
- we make the difference. If the difference is small, this is a click otherwise, this a a drag/swipe.
Example
- Variables
let startX; // start Y coordinate of the mouse
let startY; // start Y coordinate of the mouse
let element = document.querySelector('a'); // The listener element with an area
- On the mousedown, capture the start coordinates
element.addEventListener("mousedown", event => {
startX = event.pageX;
startY = event.pageY;
});
- On the mouseup, capture the end coordinates and determine if it's a click/tap or swipe/drag
element.addEventListener("mouseup", event => {
const diffX = Math.abs(event.pageX - startX);
const diffY = Math.abs(event.pageY - startY);
let eventType;
let delta = 6;
if (diffX < delta && diffY < delta) {
eventType = `Click of ${diffX}px on X`;
} else {
eventType = `Swipe of ${diffX}px on X`;
}
console.log(`It was a ${eventType}`);
});
- The HTML
<a>Click or swipe in the area</a>
element.addEventListener("click", event => { event.preventDefault(); } );