Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

The Event Object Video

In the video, Guil Hernandez says...

"In the last video you learn how events bubble up the DOM tree. For example clicking a list item also triggers a click event on the UL element containing the list item. This is useful because we can add an event listener to a parent element and let it handle events on its children."

I got really confused when he said that last part, "This is useful because we can add an event listener to a parent element and let it handle events on its children." I thought event bubbling happened when parents get affected by event handlers of their children. However, I don't get why he mentioned that we could simply add an event listener to a (PARENT ELEMENT) in order to let it handle events on it's children....???

I'm truly confused and I would appreciate it if somebody could please explain. Thanks in advance!

https://teamtreehouse.com/library/the-event-object-2

1 Answer

Michael Barlow
Michael Barlow
34,317 Points

Let's say you have a form or other element that has several clickable children. If you want to perform different actions depending on which child is clicked it may be useful to simply listen for the 'click' event in the parent and check the value of event.target. Keep in mind, though, that the click event handler on the parent will be called for any click event within its bounds, even if the target isn't one of the children.

Otherwise, you'd need to add click listeners to each of the children separately. There's no hard rule about when to choose one method over the other; it simply depends on your needs. The important point is that certain events (not the handlers) will propagate up the DOM tree and can be handled/captured at multiple points as opposed to events like 'focus' that do not bubble.