3

I have a div that has pointerdown event listener and I would like to simulate pointer down event by script. How do I do that?

Shayan
  • 57
  • 1
  • 6

2 Answers2

3

MDN spec for creating & triggering events:

// create a specific "pointerdown" event
var myEvent = new PointerEvent('pointerdown')

// Listen for the event (POC)
document.body.addEventListener('pointerdown', console.log);

// Dispatch the event (on the "<body>" element)
document.body.dispatchEvent(myEvent );

As you can see I am using the PointerEvent constructor.

Different events have different constructors, and you need to look which one has a constructor, and if there's none, you should use CustomEvent constructor.


Probably 99% of any DOM-related questions are already answered on MDN docs, you only need to connected the pieces together.

vsync
  • 118,978
  • 58
  • 307
  • 400
  • your solution is available when I want to create new event but I'd like to dispatch existing Event so I can't get that event and dispatch it. the div has pointerdown event listener and I want to click on an image to simulate pointerDown event for that div. – Shayan Apr 02 '20 at 09:01
  • @Shayan - You first must *create* an event in order to *dispatch* it. There is no "existing" event. What is stopping you from using my answer? In what **exact** way does it not help? – vsync Apr 02 '20 at 11:32
0

Try something like this:

const el = document.querySelector('#my-element');

el.addEventListener('pointerdown', (event) => {
  console.log('Pointer down event');
});

const button = document.querySelector('button');

button.addEventListener('click', () => {
  el.dispatchEvent(new PointerEvent("pointerdown"));
});
<div id="my-element">Hello world</div>
<button type="button">Simulate event</button>

For reference, MDN has documentation on simulating events.

Cameron Little
  • 3,487
  • 23
  • 35