Reputation: 41
Suppose there is a div which contains a link ( a href) and there are three event listeners - on-click- 1) for the entire page, 2) on div 3) a tag. If the user clicks on the a tag, how are the listeners triggered? What is the order of them being registered?
Upvotes: 4
Views: 1980
Reputation: 743
Essentially, it depends. There are 2 phases for events, Capturing (happens first), which goes document down, and Bubbling which goes element up.
JS can do both, which is why when creating a custom Event listened you have the third boolean variable, e.g.
parent.addEventListener('click',doSomething2,true)
child.addEventListener('click',doSomething,false)
If its last argument is true the event handler is set for the capturing phase, if it is false the event handler is set for the bubbling phase.
Referring back to the sample code and to quote this page:
If the user clicks on the child element the following happens:
The click event starts in the capturing phase. The event looks if any ancestor element of child has a onclick event handler for the capturing phase.
The event finds one on parent. doSomething2() is executed.
The event travels down to the target itself, no more event handlers for the capturing phase are found. The event moves to its bubbling phase and executes doSomething(), which is registered to child for the bubbling phase.
The event travels upwards again and checks if any ancestor element of the target has an event handler for the bubbling phase. This is not the case, so nothing happens.
The page I linked above has way more information, but hopefully that answers the basic question.
Upvotes: 5