mgabz
mgabz

Reputation: 733

How to simulate touch gestures in browser, preferably chrome?

The purpose of this question is to learn how to test JS event listeners for touch events on mobile devices.

Upvotes: 17

Views: 54989

Answers (5)

Sharkfin
Sharkfin

Reputation: 156

First, make sure your devtools is simulating touch (in Chrome, enter responsive mode and choose a mobile device). After that, this is how it works:

There are 4 touch events: touchstart, touchmove, touchend,touchcancel. If you want to simulate touchmove (i.e. click and move while finger is down) then you add an event listener to either the window or an element, and every firing of that event will trigger the callback you assign. The callback will receive the event as a whole, and it's a good idea to start off by console.log()-ging the whole event and seeing what is useful to you inside it.

For example a touchmove event will have an array called touches which will contain objects called touch. If there are 2 fingers down there will be two items in the array, each with a pageX and pageY property which would give you the position of that finger (although one can't simulate more than one finger in devtools - so you'd have to just use the first item([0])).

window.addEventListener("touchmove", (event) => { do something with event);

Upvotes: 0

Ariel Weinberger
Ariel Weinberger

Reputation: 2291

While on Chrome, press F12 to toggle Developer Mode.

Then, on the top-left of the developer partial, you will see a small icon saying "Toggle Device Mode" (Ctrl/CMD + Shift + M)

enter image description here

Then, you can switch between devices at the top.

enter image description here

This will mimic touch gestures made by a real device.

Upvotes: 25

Tony K.
Tony K.

Reputation: 5605

I would recommend Hammerjs's touch emulator. It gets you touch events like Chrome, but also multitouch events (pinch in particular). It's easy to install on your page while developing. I'm using it to test stuff written in Fulcro (React). Works perfectly.

Upvotes: 3

Cameron637
Cameron637

Reputation: 1719

Open up the devtools and on the topleft corner there's an icon with a screen behind a phone. Click it to enable phone mode. You will know you are in phone mode because the page will be smaller and a circle will appear where your cursor was. Clicking will simulate a touch event.

Upvotes: 2

wilsonzlin
wilsonzlin

Reputation: 2230

If you go into Developer Tools (F12), enter responsive design mode (Ctrl + Shift + M) and select a touch-enabled device, you can change it so it triggers touch events when you interact with the page (rather than mouse events).

Upvotes: 5

Related Questions