Skip to content

Instantly share code, notes, and snippets.

@channprj
Forked from cs09g/simulate.js
Created October 11, 2022 11:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save channprj/9e329ba7608a6ee7a7a1063b880efe09 to your computer and use it in GitHub Desktop.
Mouse/Touch Event Simulation
/**
* @desc It triggers mouse event.
* @param {HTMLElement} element target DOM element
* @param {string} type type of event
* @param {number} x clientX of event
* @param {number} y clientY of event
*/
export function simulateEvent(element, type, x, y) {
const mouseEvent = new MouseEvent(type, {
screenX: 0,
screenY: 0,
clientX: x,
clientY: y,
view: window,
cancelable: true,
bubbles: true,
});
element.dispatchEvent(mouseEvent);
}
/**
* @desc It triggers touch events. Also supports multiple touch events.
* @param {HTMLElement} element target DOM element
* @param {string} type type of event
* @param {Array} touches {x, y, id} position and identifier of the event
*/
export function simulateTouchEvent(element, type, touches) {
const touchEvents = [];
touches.forEach((touch) => {
touchEvents.push(new Touch({
clientX: touch.x,
clientY: touch.y,
identifier: touch.id,
target: element,
}));
});
element.dispatchEvent(new TouchEvent(type, {
touches: touchEvents,
view: window,
cancelable: true,
bubbles: true,
}));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment