Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript event handlers execution order

Having this JS code:

document.getElementById('e1').addEventListener('click', function(){alert('1');}, false);
document.getElementById('e2').addEventListener('click', function(){alert('2');}, false);
document.getElementById('e1').click();
document.getElementById('e2').click();

I'm wondering in what order will the alerts show up - will it be in the order the events were triggered by click() or could it be random?

I'm asking about documented/standardised behaviour, not about what browsers currently implement.

like image 365
Marek Sapota Avatar asked Aug 16 '11 11:08

Marek Sapota


People also ask

In what order are multiple handlers fired?

The vast majority of browser implementations (Chrome, Firefox, Opera, etc.), including IE9, fire the handlers in the order in which they were attached. IE8 and earlier do it the other way around.

In what order does event flow occur after a click '?

That is: for a click on <td> the event first goes through the ancestors chain down to the element (capturing phase), then it reaches the target and triggers there (target phase), and then it goes up (bubbling phase), calling handlers on its way.

How are event handlers invoked in JavaScript?

This event handler invokes a JavaScript code when a click action happens on an HTML element. E.g., when we click a button, a link is pushed, a checkbox checks or an image map is selected, it can trigger the onClick event handler. This event handler invokes a JavaScript code when a window or image finishes loading.


1 Answers

The alerts will be executed in order - 1 and then 2. This is because click event is synchronous (see here) - when .click() is issued the handler will be run immediately (look at the last paragraph here). So this code:

document.getElementById('e1').addEventListener('click', function(){alert('1');}, false);
document.getElementById('e2').addEventListener('click', function(){alert('2');}, false);
document.getElementById('e1').click();
document.getElementById('e2').click();
alert('3');

will produce the same result as

alert('1');
alert('2');
alert('3');
like image 95
Marek Sapota Avatar answered Sep 23 '22 07:09

Marek Sapota