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?

3
  • 1
    Does this answer your question? Hold event with javascript Commented Apr 1, 2020 at 17:39
  • NO this is mouse down event. I'd like to simulate pointer down; Commented Apr 1, 2020 at 17:42
  • 1
    possible duplicate: stackoverflow.com/q/2705583/104380 Commented Apr 1, 2020 at 17:48

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 - 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?
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.

Comments

0

To trigger a pointerdown event on a div named myDiv, simply do this:

myDiv.dispatchEvent(new PointerEvent('pointerdown'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.