Magic Lasso
Magic Lasso

Reputation: 1542

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

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

Upvotes: 7

Views: 21975

Answers (2)

maček
maček

Reputation: 77778

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.

Upvotes: 8

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

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

Upvotes: 5

Related Questions