Created
December 9, 2019 07:05
-
-
Save cs09g/f9971ed6ddb720d66deb1fc8da7c42d4 to your computer and use it in GitHub Desktop.
Mouse/Touch Event Simulation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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