DEV Community

Jesse
Jesse

Posted on

Event Propagation in Three Parts!

Part 1: Event Bubbling:

So when it comes to understanding how the EventListener object works in conjunction with event propagation, there are three basics that need to be considered:

  1. Event Bubbling
  2. Event Capture
  3. Once … 🤯

Event propagation can be a little tricky, especially if you haven’t solidified the terminology, or if you’re still struggling with understanding the DOM, or maybe just because event propagation sounds scary and is a little tricky in general. Either way, we got this! Fears aside, I’m going to break event propagation down very simplistically, just like I learned 💯.

So,

1.Let’s say you have this html:

  <div class="one">
    <div class="two">
      <div class="three">
      </div>
    </div>
  </div>
Enter fullscreen mode Exit fullscreen mode

2.Then you add this javascript:

  <script>
    const divs = document.querySelectorAll("div");
    function logText(e) {
      console.log(this.classList.value, this);
    }
    divs.forEach(div => div.addEventListener('click', logText));
  </script>
Enter fullscreen mode Exit fullscreen mode

3.And you decide to click the innermost div element (the one that’s most nested).


Query:

What class lists do you think will be logged to the console?
(Inserts Jeopardy music .. and slowly brings up the volume 🎶)

Solution:

Alt text

Wait.. three, two, one? ... Nope, hold up… 🛑 ✋🏼! What sorcery is this?

No sorcery I promise (still waiting on my Hogwarts letter🙏), this is simply an example of event bubbling.

Event Bubbling In a Nutshell:

1.The target element is located on the DOM.
2.The DOM has elements that are ‘listening’ for a trigger - something to shout "HEY I DID SOMETHING!".
3.Your trigger is ‘heard’ by an eventListener / eventHandler - ‘WHAT CHU SAY????”
4.Your listener/handler will perform the logic that’s either prescript or coded by you :D!

… But wait… what if your trigger is never heard… Oh no!

Now ask yourself:

“If an event fires in the middle of the DOM and no listener is around to handle it, does it actually execute at all?”

Answer: YUS!

I couldn’t end the above question as eloquently as preferred, however, the answer is still yes; the trigger still fires and will propagate up - bubble upwards just like an actual bubble - until it is either handled or reaches the topmost layer of the DOM (your window)!

So, in the above example, you clicked the innermost div element, it was located within the DOM, the click event was fired and the logText() function was executed. However, because of event bubbling the click event continued to propagate upwards until it reaches the upper most parent element.


Want to see it yourself?

1.Add this line to your javascript: document.body.addEventListener(‘click’, logText);
2.Refresh your page
3.Click a <div> element
4.Check out your browser’s javascript console 👀👀👀👀, which should look something like this:

Visual

P.S: To Open Your Browser’s JS Console:
- **Chrome**: Go to **View > Developer > JavaScript Console**
- **Safari**: Go to **Develop > Show JavaScript Console**
    - NOTE:You must have developer tools enabled via **Safari > Preferences > Advanced > Select the last checkbox at the bottom).**
- **Firefox**: Don’t use it much… not a hater, just like chrome dev tools. Although Firefox’s css grid tool is pretty schweet 😍. But for now, just do a quick google search. 
Enter fullscreen mode Exit fullscreen mode
Quick Visual to Help (hopefully) Picture the Process:

Alt text

  • Note that the capture phase is mentioned here, which is very, very, verrrrry similar to the bubble phase, but with one major difference:
  • Yep, you probably guessed it already (look at you go O_O!!, I’m so proud <3).
  • The direction is now REVERSED, so instead of bottom-to-top event bubbling (propagation), you now have top-to-bottom event capture.

p.s
If your guess wasn’t that the direction is reversed, then no worries! This stuff can get a bit confusing and I probably could have described it a little (or a lot) better. Stop sweating the small stuff, because you still made me proud for making it this far :)!

- More on this later :).. However, take some time to digest what you’ve learned so far.  But, before you go, I challenge you Try to think of some examples of both event propagation and event capture. 
- Again, don’t sweat the small stuff,~ if you can’t think of any examples right now, then take some time and come back, perhaps do a little searching, or try imagining something that, although might not be code related, could still fit the schematic/process described above :)!
- **HAVE FUN WITH IT!**
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
ayusopatricia profile image
Patricia Ayuso

Pretty cool Jesse. I liked your way of explaining the topic. This is a important topic for those who place the "event.stopPropagation" because it works but don't know why 😜