2

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
  • 37
  • 1
  • 5

2 Answers2

2

You can read MDN spec for Creating and triggering events:

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

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

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

As you can see I am using the PointerEvent constructor, also easily available by Googling that event for an MDN page.

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 you might have are already answered on MDN docs, you only need to connected the pieces together.

vsync
  • 103,437
  • 51
  • 275
  • 359
  • 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,132
  • 19
  • 34