onclick - How is the order of event listeners in javascript determined? -


suppose there div contains link ( href) , there 3 event listeners - on-click- 1) entire page, 2) on div 3) tag. if user clicks on tag, how listeners triggered? order of them being registered?

essentially, depends. there 2 phases events, capturing (happens first), goes document down, , bubbling goes element up.

js can both, why when creating custom event listened have third boolean variable, e.g.

parent.addeventlistener('click',dosomething2,true) child.addeventlistener('click',dosomething,false)

if last argument true event handler set capturing phase, if false event handler set bubbling phase.

referring sample code , quote this page:

if user clicks on child element following happens:

  1. the click event starts in capturing phase. event looks if ancestor element of child has onclick event handler capturing phase.

  2. the event finds 1 on parent. dosomething2() executed.

  3. the event travels down target itself, no more event handlers capturing phase found. event moves bubbling phase , executes dosomething(), registered child bubbling phase.

  4. the event travels upwards again , checks if ancestor element of target has event handler bubbling phase. not case, nothing happens.

the page linked above has way more information, answers basic question.


Comments