Dan
Dan

Reputation: 3020

Is triggering event listeners using ".click()" synchronous?

I have the following code (where there is a <button id="7"> in my HTML):

(function() {
  'use strict';
  document.getElementById(7).addEventListener("click", function(){
    console.log('clicked');
  })
  console.log('before');
  document.getElementById(7).click();
  console.log('after')
}());

When this runs in the Firefox 41 console, I would have expected

before
after
clicked

because the code would run synchronously, and then respond to the click event on the event queue once it had completed the script. Instead I get

before
clicked
after

This suggests the event is being handled synchronously?

Upvotes: 16

Views: 6974

Answers (1)

Bergi
Bergi

Reputation: 664185

Yes, the click method does synchronously run the activation steps which includes immediately firing (creating and dispatching) the event. It is not put in the event loop queue.

Upvotes: 20

Related Questions