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
event always fire before one added with addEventListener
?
If not, is there any way to give an event priority?
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
event always fire before one added with addEventListener
?
If not, is there any way to give an event priority?
Share Improve this question edited Mar 25, 2023 at 16:44 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Oct 31, 2013 at 21:03 Magic LassoMagic Lasso 1,5425 gold badges23 silver badges31 bronze badges 5 |2 Answers
Reset to default 8Yes
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
AddEventListener()
to attach listeners to the image being swapped ? – Ibrahim Najjar Commented Oct 31, 2013 at 21:23