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 Callback Functions in JavaScript Callbacks and the DOM Using the Same Callback on Multiple Elements

Kent Hefley
Kent Hefley
11,215 Points

Event Bubbling?

Andrew, in the video "Using the Same Callback on Multiple Elements," would it not have been better to utilize event bubbling and put the handler on the parent? In this case it would be the form.

4 Answers

Bruno Navarrete
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Bruno Navarrete
Full Stack JavaScript Techdegree Graduate 22,233 Points

You're right in thinking that event bubbling would trigger an event throughout every child and up to the parent. In this case though, we're trying to add classes to the individual input/textarea elements while they're selected (making the user experience a lot more reponsive).

Kent Hefley
Kent Hefley
11,215 Points

I see. That makes sense. Thank you.

Dora Tokai
Dora Tokai
16,003 Points

Event delegating is a bit tricky when it comes to 'focus' and 'blur'. You need to register them in the capturing phase:

const myForm = document.getElementById('myForm'); // I added id="myForm" to the HTML form.
const nameInput = document.getElementById('name');
const messageTextArea = document.getElementById('message');

const focusHandler = (event) => {
  event.target.className = 'highlight';
};
const blurHandler = (event) => {
  event.target.className = '';
};

myForm.addEventListener('focus', focusHandler, true);
myForm.addEventListener('blur', blurHandler, true);

You'll find some useful information here: Delegating the focus and blur events

Thank you Dora Tokai for this, I wasn't understanding why focus event wasn't firing.

For those who prefer to use event bubbling by adding the listener on the form element instead, use thed focusin and focusout event type. The focus and blur event type does not bubble(read more on mdn).

Jason Dsouza
Jason Dsouza
1,378 Points

Hey all, i was wondering whether you could explain what Event Bubbling means??