Skip to content

Instantly share code, notes, and snippets.

@huozhi
Created March 31, 2019 14:14
Show Gist options
  • Save huozhi/a3fff09c02c93e4e8f7cfa6ba3f5994e to your computer and use it in GitHub Desktop.
Save huozhi/a3fff09c02c93e4e8f7cfa6ba3f5994e 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)
}
@lucianobragaweb
Copy link

Nice and very util code. Thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment