SyntaxStudy
Sign Up
jQuery Intermediate 4 min read

Touch Events

Touch Events

Mobile browsers fire touchstart, touchmove, and touchend events. jQuery's event system handles them; use them for custom gestures.

Example
let startX, startY;
$("#swipeable").on("touchstart", function(e) {
  const t = e.originalEvent.touches[0];
  startX = t.clientX; startY = t.clientY;
});
$("#swipeable").on("touchend", function(e) {
  const t = e.originalEvent.changedTouches[0];
  const dx = t.clientX - startX, dy = t.clientY - startY;
  if (Math.abs(dx) > Math.abs(dy) && Math.abs(dx) > 50) {
    if (dx > 0) $(this).trigger("swiperight");
    else $(this).trigger("swipeleft");
  }
});
Pro Tip

e.originalEvent gives access to the native DOM event object from a jQuery event.