Event Bubbling, Capturing and Once in JavaScript.

Event Bubbling, Capturing and Once in JavaScript.

·

4 min read

Event listeners add interactive functionality to the elements in our HTML which makes them a preffered method of handling events. But what exactly happens?

When an element is clicked it triggers a response or an event in said element. It notices the moment, element, where it happens and what kind of event happened. Think of it as walking to your favorite coffee shop, making an order, waiting for your coffee and your name gets called to pick it up at the counter.

See it this way:

  • Your coffee order would be the event
  • Where? the counter
  • What kind of event will that trigger? for the barista to make it

Event bubbling ☁️

Bubbling pot

Now that we are aware of what happens we can start taking about event bubbling.

Like the name suggests the event will bubble up and affect the parent elements as well. It has a strong 'if i go we all go together' vibe.

Let's see an example, this is our HTML document and CSS respectively:

<body class="bod">

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

    <script src="script.js"></script>
</body>
html {
    box-sizing: border-box;
  }

  *, *:before, *:after { 
    box-sizing: inherit; 
  }

  div {
    width: 100%;
    padding: 90px;
  }

  .one {
    background: rgb(197, 162, 197);
  }

  .two {
    background: rgb(143, 111, 108);
  }

  .three {
    background: rgb(56, 17, 2);
  }

It's looking like this: Screenshot (137)

So now let's work on our script.js.

First we need to select the elements we'll be working with:

const divs = document.querySelectorAll('div')

We need a function to console.log the div that is receiving the event, in this case a click, and since querySelectorAll returns a NodeList to go through the elements we are using .forEach.

function logText(e){
    console.log(this.classList.value)
}

divs.forEach(div => div.addEventListener('click', logText))

Now if we click on our inner div with the class of 'three' we're going to trigger a bubbling event. Check the console.log and you'll see:

Screenshot (138)

If you click on our div with the class of two, you'll see "Two, One"...

But, why is that? Well, because it bubbles up to the parent elements, or the elements containing it and it registers like a single event happening to all of them.

How to stop event bubbling?

Well, we just add e.stopPropagation() to our function:

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

Now try clicking again, every click on each div will console.log as a single individual event for each click.

Event capturing🎣

This can be seen as the opposite as event bubbling but not quite. This happens when you click the element, for example our div three, the event climbs down the elements to reach the one that triggered the event instead of affecting the parent elements. It's practically imperceptible.

To catch this event, we need to add an option to our event handler for the capture and set it to true.

divs.forEach(div => div.addEventListener('click', logText, {capture: true}))

Once ⏹️

Like its name, it allows you to trigger an event once and then unbind itself. This is very useful, specially for a checkout option that only listens to the click once.

To try this let's add a button to our HTML:

<button> Use once and self destroy </button>

We select it in our script.js and add an eventListener with once set to true:

const button = document.querySelector('button')

button.addEventListener('click', () => {
    console.log('Click')
}, {
    once: true
})

Check your console and you'll see how it only registered the event once.


Event listeners are such a fun thing to play around in JavaScript, they're in the heart of what makes a page interactive. I really hope you found this article valuable and that you learned something new today.

As always thank you SOOO much for reading!! :)

Don't hesitate to connect with me and let me know what you think in the comments!

☕If you enjoy my content Buy me a coffee It'll help me continue making quality blogs💕

💙Follow me on Twitter to know more about my self-taught journey!

❤️ Also subscribe to my Youtube Channel !

🖤And for more content and tips on TikTok !

Feel free to check out my other series on:

💜Web Design for Beginners Series

💛Technical Writer Journey Series!