Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  56] [ 2]  / answers: 1 / hits: 19592  / 9 Years ago, tue, april 28, 2015, 12:00:00

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.


More From » onclick

 Answers
18

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.


[#66852] Monday, April 27, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
calicinthias

Total Points: 447
Total Questions: 101
Total Answers: 118

Location: Botswana
Member since Sat, Dec 31, 2022
1 Year ago
calicinthias questions
Sun, Jan 2, 22, 00:00, 2 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Mon, Aug 10, 20, 00:00, 4 Years ago
;