(ง •̀_•́)ง Ming's blog

Event Capture, Propagation, Bubbling and Once

Reference

Bubbling, Capture and Propagation

When we listen for a click event on every div and console.log(this.classList.value).

<div class="one">
 <div class="two">
  <div class="three"></div>
 </div>
</div>

Clicking on div with class three will console out “three”, “two” and “one” because when we click on three, we also click on the two that wraps around it, so on and so forth, it will keep zooming out.

When user clicks, browser starts “capture” the element that user clicks from outermost layer going down, and then function “bubbles” from element to outermost.

divs.forEach(div =>
 div.addEventListener("click", logText, {
  capture: true //default is false
 })
);

If we add a capture:true, the function will run on the way down instead of bubbling up. For example it will be “one”, “two”, “three” when we click on “one”.

function logText(e) {
 console.log(this.classList.value);
 e.stopPropagation(); // stop bubbling!
}

We can use propagation to stop bubbling. So when we click one, we get console “one”.

Once

divs.forEach(div =>
 div.addEventListener("click", logText, {
  capture: false,
  once: true
 })
);

Once: true unbinds the event after it ran once, it is the equivalent to removing the event.