Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Touch Events in JavaScript

Handle touch events in JavaScript for mobile: touchstart, touchmove, touchend, swipe, pinch zoom and long press detection, with explanation and output.

IntermediateJavaScript Events ProgramsExample 9 of 10

Open this page on a phone or use the device mode in Chrome DevTools. Add a <div id="myElement"> large enough to touch.

touch-events.js
1// Method 1: Basic touch events
2const element = document.getElementById('myElement');
3
4element.addEventListener('touchstart', function(e) {
5 console.log('Touch started');
6 console.log('Touches:', e.touches.length);
7 const touch = e.touches[0];
8 console.log('X:', touch.clientX, 'Y:', touch.clientY);
9});
10
11element.addEventListener('touchmove', function(e) {
12 e.preventDefault(); // Prevent scrolling
13 console.log('Touch moving');
14 const touch = e.touches[0];
15 console.log('Position:', touch.clientX, touch.clientY);
16});
17
18element.addEventListener('touchend', function(e) {
19 console.log('Touch ended');
20 console.log('Changed touches:', e.changedTouches.length);
21});
22
23element.addEventListener('touchcancel', function(e) {
24 console.log('Touch cancelled');
25});
26
27// Method 2: Multi-touch
28element.addEventListener('touchstart', function(e) {
29 if (e.touches.length === 2) {
30 console.log('Two finger touch');
31 const touch1 = e.touches[0];
32 const touch2 = e.touches[1];
33
34 const distance = Math.sqrt(
35 Math.pow(touch2.clientX - touch1.clientX, 2) +
36 Math.pow(touch2.clientY - touch1.clientY, 2)
37 );
38 console.log('Distance:', distance);
39 }
40});
41
42// Method 3: Swipe detection
43let touchStartX, touchStartY;
44
45element.addEventListener('touchstart', function(e) {
46 touchStartX = e.touches[0].clientX;
47 touchStartY = e.touches[0].clientY;
48});
49
50element.addEventListener('touchend', function(e) {
51 const touchEndX = e.changedTouches[0].clientX;
52 const touchEndY = e.changedTouches[0].clientY;
53
54 const deltaX = touchEndX - touchStartX;
55 const deltaY = touchEndY - touchStartY;
56
57 const minSwipeDistance = 50;
58
59 if (Math.abs(deltaX) > Math.abs(deltaY)) {
60 // Horizontal swipe
61 if (deltaX > minSwipeDistance) {
62 console.log('Swipe right');
63 } else if (deltaX < -minSwipeDistance) {
64 console.log('Swipe left');
65 }
66 } else {
67 // Vertical swipe
68 if (deltaY > minSwipeDistance) {
69 console.log('Swipe down');
70 } else if (deltaY < -minSwipeDistance) {
71 console.log('Swipe up');
72 }
73 }
74});
75
76// Method 4: Pinch zoom
77let initialDistance = 0;
78
79element.addEventListener('touchstart', function(e) {
80 if (e.touches.length === 2) {
81 const touch1 = e.touches[0];
82 const touch2 = e.touches[1];
83 initialDistance = Math.sqrt(
84 Math.pow(touch2.clientX - touch1.clientX, 2) +
85 Math.pow(touch2.clientY - touch1.clientY, 2)
86 );
87 }
88});
89
90element.addEventListener('touchmove', function(e) {
91 if (e.touches.length === 2) {
92 const touch1 = e.touches[0];
93 const touch2 = e.touches[1];
94 const currentDistance = Math.sqrt(
95 Math.pow(touch2.clientX - touch1.clientX, 2) +
96 Math.pow(touch2.clientY - touch1.clientY, 2)
97 );
98
99 const scale = currentDistance / initialDistance;
100 console.log('Scale:', scale);
101
102 if (scale > 1.1) {
103 console.log('Pinch out (zoom in)');
104 } else if (scale < 0.9) {
105 console.log('Pinch in (zoom out)');
106 }
107 }
108});
109
110// Method 5: Tap vs long press
111let pressTimer;
112
113element.addEventListener('touchstart', function(e) {
114 pressTimer = setTimeout(function() {
115 console.log('Long press detected');
116 // Handle long press
117 }, 500); // 500ms
118});
119
120element.addEventListener('touchend', function(e) {
121 clearTimeout(pressTimer);
122 console.log('Tap detected');
123});
124
125element.addEventListener('touchmove', function(e) {
126 clearTimeout(pressTimer);
127});

Sample Output

Swipe right

deltaX was about 140 pixels, more than deltaY and more than 50.

Tap detected

Method 5 logs this on every touchend because it does not know a swipe happened.

In this one

  • The four touch event types
  • The difference between touches, targetTouches and changedTouches
  • How to detect swipe and pinch
  • How a timer tells tap from long press

How it works

  1. 1

    touchstart logs the finger count and position.

  2. 2

    touchmove blocks scrolling and logs the position.

  3. 3

    touchend logs changedTouches.

  4. 4

    Two-finger touches measure the distance.

  5. 5

    Swipe compares start and end positions.

  6. 6

    Pinch compares distances and long press uses a 500 ms timer.

Edge cases

preventDefault ignored

The page still scrolls and the console warns about passive listeners.

Add the listener with { passive: false } when you must block scrolling.

Tap after a long press

touchend logs Tap detected even after Long press detected.

Set a flag in the long-press timer and skip the tap message when it is set.

Divide by zero in pinch

If two fingers did not start together, initialDistance is 0 and scale is Infinity.

Only compute scale when initialDistance is greater than 0.

What's going on

Touch events let phones and tablets react to fingers. Mobile apps, touch games and gesture controls all use them.

There are four types. touchstart fires when a finger touches the screen. touchmove fires as it moves. touchend fires when it lifts. touchcancel fires when the system interrupts the touch, for example when a call comes in.

Each event has lists of touches. touches holds all fingers on the screen. targetTouches holds fingers on this element. changedTouches holds fingers that changed in this event. Each touch has clientX and clientY. In touchend, the finger has already left, so touches may be empty. Use changedTouches there, as the swipe code does.

Method 1 logs basic touch info. touchmove calls preventDefault() to stop the page from scrolling while you drag. For that to work, many browsers need the listener added with { passive: false }.

Method 2 detects two fingers and measures the distance between them with the Pythagoras formula.

Method 3 detects a swipe. It saves the start point on touchstart and compares it with the end point. If the horizontal move is bigger than the vertical one, it is a left or right swipe. A minimum distance of 50 pixels stops tiny moves from counting.

Method 4 detects pinch. It divides the current finger distance by the starting distance. A scale above 1.1 means fingers moved apart, zoom in. Below 0.9 means pinch in, zoom out.

Method 5 tells a tap from a long press. A 500 ms timer starts on touchstart. If the finger lifts or moves first, the timer is cleared.

Gestures covered: tap, long press, swipe and pinch. Best practices: prevent default for custom gestures, handle multi-touch, use changedTouches in touchend, and test on real devices.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which list should you read in touchend?

Pick an answer to check it.

Question 2

A pinch scale of 1.3 means?

Pick an answer to check it.

Questions people ask

Should I use touch or pointer events?

Pointer events handle mouse, pen and touch together. Touch events are still useful for multi-finger gestures.

Why use changedTouches in touchend?

The lifted finger is no longer in touches.

Can I test without a phone?

Yes, Chrome DevTools device mode simulates touch, but real devices are best.