Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onClick priority over addEventListener in javascript?

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

<script>
document.body.addEventListener('click',function(){alert('1');}, false);

function clicked() { 
    alert('2');
}
</script>
<button onclick="clicked()">Click this</button>

Clicking the button also triggers the event handler. 1 shows before 2, when I click the button. I want 2 to show first.

like image 641
BlueElixir Avatar asked Apr 28 '15 14:04

BlueElixir


People also ask

How do you prioritize events in JavaScript?

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.

What is eventListener in JavaScript?

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.


1 Answers

addEventListner's third argument is the useCapture flag. If you set it to true, handler will be executed while the event is traveling down to the button element. However, if you set it to false, the handler will be triggered while the event is bubbling up:

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

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

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

like image 76
musically_ut Avatar answered Sep 19 '22 15:09

musically_ut