Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript 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 even always fire before one added with addEventListener?

If not, is there any way to give an event priority?

like image 677
Magic Lasso Avatar asked Oct 31 '13 21:10

Magic Lasso


2 Answers

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.

like image 139
maček Avatar answered Oct 08 '22 23:10

maček


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

like image 38
Ibrahim Najjar Avatar answered Oct 09 '22 00:10

Ibrahim Najjar