9

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Marek Sapota
  • 20,103
  • 3
  • 34
  • 47
  • `click();` won't work, by the way; that is not the way to fire events. You need to use `createEvent`, `initEvent` and `dispatchEvent`. – Delan Azabani Aug 16 '11 at 11:04
  • 1
    No I don't. http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-2651361 – Marek Sapota Aug 16 '11 at 11:25
  • In this instance, okay, but this method of firing events is far from universal for availability with regards to all events on all elements. The only reliable way to fire events is to use the three methods I have mentioned above. – Delan Azabani Aug 16 '11 at 11:34
  • Actually in HTML5 you can use `click` on any element http://www.w3.org/TR/html5/elements.html#htmlelement But I agree that it's not universally supported in browsers right now. – Marek Sapota Aug 16 '11 at 11:49
  • Nor is create/dispatch event. – RobG Aug 16 '11 at 13:12

2 Answers2

3

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');
Marek Sapota
  • 20,103
  • 3
  • 34
  • 47
-1

I will be 1 and then 2 . http://jsfiddle.net/kkYfX/

Anil Shanbhag
  • 950
  • 1
  • 13
  • 31
  • Not sure how e2 click could trigger alert before e1 click does ? – Anil Shanbhag Aug 16 '11 at 11:08
  • Because event handlers don't run immediately when `click()` is executed. They run "some time" after that - possibly be in different order. – Marek Sapota Aug 16 '11 at 11:29
  • @maarons - the second must be called after the first. The only foible might be if bubbling of the first causes the other to be called before it is called by the second statement. But in that case it will be called twice, and always after the first. If the listener is set to fire on the capture phase, things might be different but that isn't what the code is doing. – RobG Aug 16 '11 at 13:22