With the different ways of adding events in javascript, do any of them take priority like css classes do? For example will an inline onclick even always fire before one added with addEventListener?
If not, is there any way to give an event priority?
Yes
An inline onclick
handler is going to bind as the DOM is loading
Whereas anything you add with .on
or .addEventListener
will have to wait for the DOM element to load first.
See here: http://jsfiddle.net/DmxNU/
Your html
<a href="#" onclick="console.log('hello');">click</a>
Your js (jQuery in this case)
$(function() {
$("a").click(console.log.bind(console, "world"));
});
Output
hello
world
Explanation
I'm not sure where this would be documented, but think about it this way. If you're going to use the DOM API to query an element and then add an event listener, that element has to be loaded first. If that element already contains an onclick
attribute, that will already be attached first.
JavaScript events don't take any priorities. When and event is fired it is added to an event queue and executed as soon as possible.
You can claim that it is a general rule that onclick attribut events will always trigger first, and that will always be true, but it's not because they are prioritized.
Quoted from @Kevin B's comment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With