OnClick priority over addEventListener in javascript?

I now have an event listener that listens for a click on the screen. There is a button on the screen. When I click the button, the event listener will execute before onclick. Is there a way to force onclick to have a higher priority?

<script> document.body.addEventListener('click',function(){alert('1');}, false); function clicked() { alert('2'); } </script> <button onclick="clicked()">Click this</button> 

Pressing a button also launches an event handler. 1 shows up to 2 when I press the button. First I want to show 2.

+6
source share
2 answers

addEventListner The third argument is useCapture flag . If you set it to true , the handler will be executed when the event moves down to the button element. However, if you set it to false , the handler will fire while the event bubbles up:

  capture phase | | / \ bubbling up -----------------| |--| |----------------- | element1 | | | | | | -------------| |--| |----------- | | |element2 \ / | | | | | -------------------------------- | | W3C event model | ------------------------------------------ 

From: http://www.quirksmode.org/js/events_order.html#link4

In your example, onclick should be executed before the click handler in the body tag . If you want to change the order of execution, you must capture event in the body .

+12
source

One solution would be to use inline in different ways. When the .addEventListener needs to wait for the DOM, on the other hand, the inline onclick binds during the loading of the DOM.

 <script> document.body.addEventListener('click',function(){alert('1');}, false); function clicked() { alert('2'); } </script> <button onclick="alert('2');">Click this</button> 

JSFIDDLE: http://jsfiddle.net/8j9q23jw/

0
source

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


All Articles