Search code examples
typescriptmouseeventdispatchevent

How to dispatch Mouse event with fixed X and Y Typescript


I am trying to dispatch a mouse Event with fixed X and Y variables to test some things. It is the only way to do it. I want to dispatch a mouse Event where I can set the X and Y in programm code upon calling the window.dispatchEvent function.

Something like this would be great:

var ev: Event = new Event(100,200); window.dispatchEvent(ev);

I have tried a lot of things but I couldn't find any way to solve this issue. Any help would be appreciated


Solution

  • Create the MouseEvent of the type you like with the clientX and clientY properties configured as follows:

    const event = new MouseEvent('mousedown', {
      clientX: 100,
      clientY: 200
    });
    
    window.addEventListener('mousedown', (e) => console.log(e.clientX, e.clientY));
    
    window.dispatchEvent(event);