Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Callback Functions in JavaScript Callbacks and the DOM Using the Same Callback on Multiple Elements

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

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).

I see. That makes sense. Thank you.

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).

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