Skip to content

Instantly share code, notes, and snippets.

@cs09g
Created December 9, 2019 07:05
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save cs09g/f9971ed6ddb720d66deb1fc8da7c42d4 to your computer and use it in GitHub Desktop.
Save cs09g/f9971ed6ddb720d66deb1fc8da7c42d4 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