This is the 28th day of my participation in the August Text Challenge.More challenges in August

Preface:

Hello again, I’m Loncon, a pioneer on the road, and let’s get started on today’s topic: frequent interview topics, event bubbling, event capture and event flow.

The event bubbling

An event for an element fires, and that event fires in sequence (from inside to outside) in all of the element’s ancestors, a process known as event bubbling

In plain English: when we fire an event of a child element, the event corresponding to the parent element also fires. Bubbling all the way to document.

<body> <div class="father"> <div class="son"> <div class="sun"></div> </div> </div> <script> var fa = document.querySelector('.father'); var so = document.querySelector('.son'); var su = document.querySelector('.sun'); Fa.onclick = function () {console.log(' parent element was triggered '); }; So. Onclick = function () {console.log(' child element fired '); }; Su. Onclick = function () {console.log(' grandson was triggered '); }; </script> </body>Copy the code

Benefits of bubbling:

// Event bubble can delegate multiple events to a parent element to implement event delegation.

// Combine the event object attribute target <body> <ul> <li> I am the first li</li> <li> I am the second li</li> <li> I am the third li</li> <li> I am the fourth li</li> <li> I am the fifth li</li> <li> I'm the sixth li</li> <li> I'm the seventh li</li> <li> I'm the eighth li</li> <li> I'm the tenth li</li> </ul> <script> var ul = document.querySelector('ul'); ul.onclick = function (e) { e.target.style.backgroundColor = 'red'; //e.target refers to the element that the user clicked on, but the code structure should be clear, and layer nesting is recommended not to use this}; </script> </body>Copy the code

To prevent a bubble

1. Determine to whom the propagation of the event will stop (usually the current triggered element, or ancestor element) 2. 3. Accept the event object in the event handler and add e.topPropagation ().Copy the code
document.onclick = function(){ box.style.display = 'none' } box.onclick = function(){ e.stopPropagation(); } // Prevent bubbling in box, no subsequent bubbling in documentCopy the code

Event capture

An event for an element is triggered, and that event is triggered internally (from outside to inside) in the element's ancestor elements.Copy the code
AddEventListener (type,func,useCapture) First argument: event type, click, mousemove Second argument: function, listener, each click, this function executes the third argument: Btn.addeventlistener ('click',function(){console.log(' I am event capture '); },true)Copy the code

Flow of events

Phase 1: capture phase Phase 2: source of events triggered by the target phase Phase 3: Bubble Phase The third parameter of addEventListener can be used to determine whether an element’s event is triggered in the bubble or capture phase. True: the capture phase is triggered