Ozan Yılmaz
Ozan Yılmaz

Reputation: 130

What is the difference between eventTarget.click() and eventTarget.dispatchEvent(new Event("click"))?

When I run both codes in the console, eventTarget.click() returns undefined but actually clicks the target element whereas eventTarget.dispatchEvent(new Event("click")) returns true but doesnt click the target element. I am trying to understand but I cant figure out why there are 2 different outcomes. Can you please explain why and how they are different? Arent both of them supposed to click the element on the page?

document.getElementById("button").click()

and

document.getElementById("button").dispatchEvent(new Event("click"))

Upvotes: 6

Views: 2773

Answers (1)

A Paul
A Paul

Reputation: 8261

The click() method is used to simulate a mouse click on the element. It fires the click event of the element on which it is called. The event bubbles up to elements higher in the document tree and fires their click events also.

The Event constructor is used to create a new event to be used on any element. The ‘click’ event can be passed to the constructor of Event to create a click event. This created Event has various properties which can be accessed to customize the event.

I will suggest using the MouseEvent instead of Event. Check below example

document.getElementById('eventTarget').click()
alert('before next')
document.getElementById('eventTarget').dispatchEvent(new MouseEvent("click"))
<input type="button" value="test" id="eventTarget" onclick="alert('clicked');"/>

Upvotes: 5

Related Questions