Home > Net >  How to override mouse event with touch event using javascript?
How to override mouse event with touch event using javascript?

Time:10-05

I'm trying to simulate the touch events in a react.js application. The goal is to trigger touch events instead of mouse ones (i.e. mouseDown should trigger touchStart, etc.).

The behavior I'm trying to replicate is the same one as when you're using the Chrome dev tool console on mobile view.

CodePudding user response:

You can create an event with the class Event. Then you can dispatch the event on a dom element or on window

const clickEvent = new Event('touchStart', {"bubbles":true})
window.dispatchEvent(clickEvent);

Here is a long article that covers these 2 lines of code: https://medium.com/@gianfranconuschese/simulating-events-with-javascript-c62da15422b2

so basically you could use window.addEventListener('mouseDown', eventHandler) where eventHandler would be a function that calls the two lines of code I shared earlier

  • Related