Skip to content

Instantly share code, notes, and snippets.

@ken107
Last active December 8, 2021 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ken107/c56c6a69bf3c18995af8a02ec875900c to your computer and use it in GitHub Desktop.
Save ken107/c56c6a69bf3c18995af8a02ec875900c to your computer and use it in GitHub Desktop.
function simulate(element, eventName, options) {
var opt = {
pointerX: 0,
pointerY: 0,
button: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
bubbles: true,
cancelable: true
}
Object.assign(opt, options)
var oEvent
switch (eventName) {
case "unload":
case "abort":
case "error":
case "select":
case "change":
case "submit":
case "reset":
case "focus":
case "blur":
case "resize":
case "scroll":
oEvent = document.createEvent("HTMLEvents")
oEvent.initEvent(eventName, opt.bubbles, opt.cancelable)
break
case "click":
case "dblclick":
case "mousedown":
case "mouseup":
case "mouseover":
case "mousemove":
case "mouseout":
case "keydown":
case "keyup":
oEvent = document.createEvent("MouseEvents")
oEvent.initMouseEvent(eventName, opt.bubbles, opt.cancelable, document.defaultView,
opt.button, opt.pointerX, opt.pointerY, opt.pointerX, opt.pointerY,
opt.ctrlKey, opt.altKey, opt.shiftKey, opt.metaKey, opt.button, element)
break
default:
throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported')
}
element.dispatchEvent(oEvent)
}
/* https://stackoverflow.com/a/51893135/226844
*/
function simulateClick(elementToClick) {
var simulateMouseEvent = function(element, eventName, coordX, coordY) {
element.dispatchEvent(new MouseEvent(eventName, {
view: window,
bubbles: true,
cancelable: true,
clientX: coordX,
clientY: coordY,
button: 0
}));
};
var box = elementToClick.getBoundingClientRect(),
coordX = box.left + (box.right - box.left) / 2,
coordY = box.top + (box.bottom - box.top) / 2;
simulateMouseEvent (elementToClick, "mousedown", coordX, coordY);
simulateMouseEvent (elementToClick, "mouseup", coordX, coordY);
simulateMouseEvent (elementToClick, "click", coordX, coordY);
}
@ken107
Copy link
Author

ken107 commented Aug 20, 2021

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