Skip to content

Instantly share code, notes, and snippets.

@elzii
Forked from huozhi/simulate_mouse_action.js
Created April 21, 2023 17:53
Show Gist options
  • Save elzii/acd74e294384fb45876120dd10bc2222 to your computer and use it in GitHub Desktop.
Save elzii/acd74e294384fb45876120dd10bc2222 to your computer and use it in GitHub Desktop.
simulate click and hover mouse action on web with js
const mouseEventOf = (eventType) => (element, x, y) => {
const rect = element.getBoundingClientRect()
const event = new MouseEvent(eventType, {
view: window,
bubbles: true,
cancelable: true,
clientX: rect.left + x,
clientY: rect.top + y,
})
element.dispatchEvent(event)
}
function clickOnElement(element, x, y) {
mouseEventOf('click')(element, x, y)
}
function hoverOnElement(element, x, y) {
mouseEventOf('mousemove')(element, x, y)
mouseEventOf('mouseover')(element, x, y)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment