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

Juneau Lim
Juneau Lim
13,362 Points

can't we make it even simpler?

I wanted to make it even simpler by putting class as arguments, since the difference between to function was just class name.

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

const blurHandler = event => {
  event.target.className = '';
}

I tried this but below gave me an error.

const nameInput = document.getElementById('name');
const messageTextArea = document.getElementById('message');

const focusToggler = (event, class) => {
  event.target.className = class;
}

nameInput.addEventListener('focus', focusToggler(this, highlight));    // not so sure what to put instead of this.

Uncaught SyntaxError: Unexpected token )

Not only I get error early, but an also not sure if putting this there would work. is there a way to do something like this?

1 Answer

tomd
tomd
16,701 Points

This line of code you are actually calling the focusToggler function

nameInput.addEventListener('focus', focusToggler(this, highlight));

you'll need to write something like this, also notice how highlight is now a string.

nameInput.addEventListener('focus', function(event){
 focusToggler(event, 'highlight');
});

Whats happening here is im assigned an anonymous function and once the input gets focus it'll call that anonymous function which will then call focusToggler and pass in the arguments.

Juneau Lim
Juneau Lim
13,362 Points

Wow, awesome! Glad there is a way! Thanks for the solution!

Cornelius Hager
Cornelius Hager
5,659 Points

I had the same issue as Juneau. The solution was helpfull.

But, why do we have to use the extra anonymous function here? Why can't we pass ** focusToggler (event, highlight)** directly as a callback function?