dark mode

How to separate Drag and Swipe from Click and Touch events

How to separate Drag and Swipe from Click and Touch events

Gestures like swipe and drag events are a great way to introduce new functionalities into your app. However, sometimes is difficult to distinguish dragging from clicking on a desktop or swiping from tapping on a mobile.

There is no onDrag or onSwipe events so we need to catch them through logic. Below are snippets of code in React and in pure Javascript. In both cases we have a boolean variable or in react a state variable called isSwipe.

First step, is when we touch the screen or press and hold the mouse button. On this step we are setting isSwipe to false, because there is no movement. On the second step we track if there is a movement before we stop holding the mouse button or not touching the screen. If that is the case we set isSwipe to true. The final step is where we check when we stop holding the mouse button or touching the screen. We also have an additional check to see if we are using the left button in the mouse event. Sometimes when running on mobile the mouse event fired, which breaks our logic, to prevent that on touchend event we add preventDefault. Finally, in the if statement we can introduce our app logic and reset the variable to false.

In React

const [isSwiping, setSwiping] = useState(false);

return (
  <div
    onMouseDown={() => {
      setSwiping(false);
    }}
    onMouseMove={() => {
      setSwiping(true);
    }}
    onMouseUp={e => {
      if (!isSwiping && e.button === 0) {
        console.log('dragging');
      } else {
        console.log('not dragging');
      }

      setSwiping(false);
    }}
    onTouchStart={() => {
      setSwiping(false);
    }}
    onTouchMove={() => {
      setSwiping(true);
    }}
    onTouchEnd={e => {
      e.preventDefault();

      if (!isSwiping) {
        console.log('swiping');
      } else {
        console.log('not swiping');
      }

      setSwiping(false);
    }}
  ></div>
);

Pure Javascript

let isSwiping = false;

document.getElementById('demo').addEventListener('mousedown', () => {
  this.isSwiping = false;
});

document.getElementById('demo').addEventListener('mousemove', () => {
  this.isSwiping = true;
});

document.getElementById('demo').addEventListener('mouseup', e => {
  if (this.isSwiping && e.button === 0) {
    console.log('dragging');
  } else {
    console.log('not dragging');
  }

  this.isSwiping = false;
});

document.getElementById('demo').addEventListener('touchstart', () => {
  this.isSwiping = false;
});

document.getElementById('demo').addEventListener('touchmove', () => {
  this.isSwiping = true;
});

document.getElementById('demo').addEventListener('touchend', e => {
  e.preventDefault();

  if (this.isSwiping) {
    console.log('swiping');
  } else {
    console.log('not swiping');
  }

  this.isSwiping = false;
});

Related articles

© 2021 All rights reserved.