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?
Asked
Active
Viewed 6,647 times
3
-
Does this answer your question? [Hold event with javascript](https://stackoverflow.com/questions/27402897/hold-event-with-javascript) – Shane Creedon Apr 01 '20 at 17:39
-
NO this is mouse down event. I'd like to simulate pointer down; – Shayan Apr 01 '20 at 17:42
-
possible duplicate: https://stackoverflow.com/q/2705583/104380 – vsync Apr 01 '20 at 17:48
2 Answers
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