Event Propagation in Three Parts!

Jesse - Oct 31 '19 - - Dev Community

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
. . .
Terabox Video Player