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?
-
1Does this answer your question? Hold event with javascriptShane Creedon– Shane Creedon2020-04-01 17:39:54 +00:00Commented Apr 1, 2020 at 17:39
-
NO this is mouse down event. I'd like to simulate pointer down;Shayan– Shayan2020-04-01 17:42:02 +00:00Commented Apr 1, 2020 at 17:42
-
1possible duplicate: stackoverflow.com/q/2705583/104380vsync– vsync2020-04-01 17:48:16 +00:00Commented Apr 1, 2020 at 17:48
Add a comment
|
3 Answers
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 connect the pieces together.
2 Comments
Shayan
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.
vsync
@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?
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.