0

I want to dispatch a mouse event, just as if a user clicked a point on the screen. I do not know the target, I just have the coordinates. How do I dispatch it? I tried this, but it does not seem to work.

const mouseEv = new MouseEvent("click", {
    screenX: X,
    screenY: Y,
});
window.dispatchEvent(mouseEv);
document.dispatchEvent(mouseEv);
document.documentElement.dispatchEvent(mouseEv);
Leo
  • 4,136
  • 6
  • 48
  • 72
  • 1
    Is the problem that you need to figure out which element that X and Y will be pointing at, so you can dispatch the event to that element? – CertainPerformance Jan 02 '20 at 04:24
  • @CertainPerformance Do you mean I should use `getElementFromPoint` (or what it is called)? Yes, I could do that but I would prefer to send the mouse event. – Leo Jan 02 '20 at 04:26
  • 1
    Yes, identify the element, and then send the mouse event to that element - that sounds like what you want? – CertainPerformance Jan 02 '20 at 04:27
  • @CertainPerformance Yes, but it seems a bit unnecessary work. And I would like to use the coordinates the same way as if the user clicked. (It will be a new contenteditable element.) But maybe that works the way you suggests? – Leo Jan 02 '20 at 04:30
  • 1
    You have to identify the topmost element in the window at that point anyway, a single function call to figure that out isn't too tedious. Then just call `dispatchEvent` on that element (it'll capture/bubble for you, no need to specify every element between it and the top element) – CertainPerformance Jan 02 '20 at 04:32
  • @CertainPerformance Ok, thanks. I was not sure. – Leo Jan 02 '20 at 04:34
  • @CertainPerformance Hm. It kind of works, but not as if the user clicked at that point. (Which was part of the trouble I wanted to avoid. But maybe that is not possible.) – Leo Jan 02 '20 at 04:56

0 Answers0