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?
Advertisement
Answer
(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>