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?
Event handlers are really a form of asynchronous programming: you provide a function (the event handler) that will be called, not right away, but whenever the event happens.
That's correct. All event handlers are fired synchronously and in order of binding.
Because these events happen at unpredictable times and in an unpredictable order, we say that the handling of the events, and therefore the invocation of their handling functions, is asynchronous.
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With