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 Callbacks on Text Inputs

Brian Anstett
Brian Anstett
5,831 Points

Function declaration for callback instead of an arrow function.

When I declare a function to be used as the callback before the addEventListener, I do not get the correct results. I must be missing something in my understanding because I can't see why the following code wouldn't work.


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

function focus(e){ e.target.className = 'highlight'; }

nameInput.addEventListener('focus', focus(event)); nameInput.addEventListener('blur', event => event.target.className = '');


NOTE: I get the correct results when using an arrow function as the callback.

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

function focus(e){ e.target.className = 'highlight'; }

nameInput.addEventListener('focus', event => event.target.className = 'highlight'); nameInput.addEventListener('blur', event => event.target.className = '');

Brian Anstett
Brian Anstett
5,831 Points

After watching the next video, I was reminded I just need the name of the callback function. So it was unnecessary of me to provide "(event)".

1 Answer

Steven Parker
Steven Parker
231,248 Points

It's not just unnecessary, it causes an error. When you put parentheses after a function name (with or without arguments), you are invoking ("calling") the function immediately and passing the function's return value as the argument.

But for a callback, you want to pass the function itself, so it's important to not use the parentheses.