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.
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.
Share Improve this question edited Jan 23, 2024 at 0:00 starball 53.9k34 gold badges235 silver badges927 bronze badges asked Aug 16, 2011 at 11:03 Marek SapotaMarek Sapota 20.6k3 gold badges36 silver badges48 bronze badges 5-
click();
won't work, by the way; that is not the way to fire events. You need to usecreateEvent
,initEvent
anddispatchEvent
. – Delan Azabani Commented Aug 16, 2011 at 11:04 - 1 No I don't. w3/TR/DOM-Level-2-HTML/html.html#ID-2651361 – Marek Sapota Commented Aug 16, 2011 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 Commented Aug 16, 2011 at 11:34
-
Actually in HTML5 you can use
click
on any element w3/TR/html5/elements.html#htmlelement But I agree that it's not universally supported in browsers right now. – Marek Sapota Commented Aug 16, 2011 at 11:49 - Nor is create/dispatch event. – RobG Commented Aug 16, 2011 at 13:12
2 Answers
Reset to default 3The 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');
I will be 1 and then 2 . http://jsfiddle/kkYfX/