Detect Finger Swipe Events with JavaScript

02/08/2022

Contents

In this article, I will introduce how to detect finger swipe events with JavaScript.

Detect finger swipe events

To detect finger swipe events on iOS and Android, use a combination of “touchstart”, “touchmove” and “touchend” of “addEventListener”.

Use “touchstart” to get the touch start position of the swipe, and “touchmove” to get the touch position of the destination at any time.
Finally, at the timing of “touchend”, the start position and the destination position are compared, and if there is a certain amount of movement, it is judged as a swipe.

Sample Code

Below is sample code for detecting horizontal finger swipe events.

function detectSwipe(elem) {
  let t = document.querySelector(elem);
  let s_X;
  let e_X;
  let dist = 30;
  t.addEventListener('touchstart', function(e) {
    e.preventDefault();
    s_X = e.touches[0].pageX;
  });
  t.addEventListener('touchmove', function(e) {
    e.preventDefault();
    e_X = e.changedTouches[0].pageX;
  });
  t.addEventListener('touchend', function(e) {
    if (s_X > e_X + dist) {
      t.textContent = 'Swipe left';
    } else if (s_X + dist < e_X) {
      t.textContent = 'Swipe right';
    }
  });
}
detectSwipe('.swipearea');