What is the order of the built-in onclick vs addeventlistener and why?

Consider this button:

<button id="the_button" onclick="RunOnClick();">Click</button>

This button has a built-in event handler onclick. The contents of the function are RunOnClicknot relevant for this question.

If I ALSO attach another click event listener, for example:

var btn = document.getElementById('the_button');

btn.addEventListener("click", function(){
    // Do Something
});

It seems that the handler registered in addEventListeneralways starts after the built-in onclick="".

Can I always rely on one built-in handler onclickfor the addEventListenerfirst, and a handler addEventListenerfor addEventListenerlater?

It is an accident? Or is this really part of one of the ECMAScript specifications?

This seems like a return to the basic quality of the question, but I do not know the answer.

+6
source share
3

: , , ECMAScript , ECMAScript .

-, DOM. SO.

JavaScript ?

, , DOM level 3 spec, , .

, ?

HTML 5, :

- . content .

[...]

H T, EventTarget, , , T , , H callback, , .

:

  • (, onclick) , DOM, .
  • , , , , onclick, .
  • , null, . ( ).

. , .

-, , , , , . inline, . , , , . addEventListener, addEventListener , . .

, . HTML5, :

8

, . , "ONE", "TWO", "THREE" "FOUR" .

 <button id='test'>Start Demo</button>
    <script>
    var button = document.getElementById('test');
    button.addEventListener('click', function () { alert('ONE') }, false);
    button.setAttribute('onclick', "alert('NOT CALLED')"); // event handler listener is registered here
    button.addEventListener('click', function () { alert('THREE') }, false);
    button.onclick = function () { alert('TWO'); };
    button.addEventListener('click', function () { alert('FOUR') }, false);
    </script>

, onclick , onclick - addEventListener. , inline , . , , , , , , .

JSFiddle, , , , Firefox, Chrome.


, :

  • , , , .
  • , , , setAttribute, , addEventListener.
  • .

, !

+6

, , ... browswer, . , - ! , , - .

, : , , , , . - , . , , .

, , - .

+1

While the behavior may be repeated in the browser you are using, it does not guarantee that another browser - or even another version of the same browser - will act the same.

This is because each rendering engine sets its own priority for running event handlers, usually in the order in which they are attached.

If you need to provide a specific order of execution, you can configure an event queue that runs on a single handler.

-1
source

Source: https://habr.com/ru/post/1696128/


All Articles