Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Event Listeners - Firing order

If an element has multiple event listeners attached, will the order of execution be based on where/when the events are bound (located in the code from top to bottom). Guaranteed, 100% of the time?

Or is there any "randomness" involved in this. What about mixing jQuery and vanilla event listeners on the same element?

like image 248
Bruffstar Avatar asked Aug 06 '15 09:08

Bruffstar


Video Answer


1 Answers

(Assuming you are talking about the same event type and element)The event handlers will get executed in the order in which the handlers are registered. This is true when you are dealing with either jQuery handles or javascript handlers(the capture phase runs before bubbling) alone, not mixed.

When you have mixed handlers, jQuery will add a vanila handler when it tries to register a handler of a type for the first time for an element, so it will follow the order of vanilla handlers in order(but all the jQuery handlers will be executed when the jQuery's own native handler is triggered)

var el = document.getElementById('clickme');

el.addEventListener('click', function() {
  snippet.log('o - 1');
});
el.addEventListener('click', function() {
  snippet.log('o - 2');
});

$('#clickme').click(function() {
  snippet.log('jq - 1(o -3)')
});
el.addEventListener('click', function() {
  snippet.log('o - 4');
});
$('#clickme').click(function() {
  snippet.log('jq - 2')
});
$('#clickme').click(function() {
  snippet.log('jq - 3')
});
el.addEventListener('click', function() {
  snippet.log('o - 5');
});
el.addEventListener('click', function() {
  snippet.log('o - 6');
});
$('#clickme').click(function() {
  snippet.log('jq - 4')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<button id="clickme">This is for testing</button>
like image 83
Arun P Johny Avatar answered Oct 18 '22 15:10

Arun P Johny