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 JavaScript and the DOM (Retiring) Responding to User Interaction Functions as Parameters

Jan Livny
Jan Livny
6,705 Points

Functions in event listeners

Hello,

Is it an obligation to use a function inside an event listener:

MyButton.addEventListener("click", () => {myHeading.style.color = "red"})

Or is it a style/ good practice thing, if so can I simply use:

MyButton.addEventListener("click", myHeading.style.color = "red")

Thanks in advance,

Jan

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points

Yes, you pretty much have to use a function, cannot use a statement. In the example you provided, the statement will immediately run setting myHeading.style.color to "red". It won't wait for a click event to happen, it will happen as soon as the script loads. You also can see this error in the console:

The callback provided as parameter 2 is not an object.

Technically speaking, you could also use object implementing the EventListener interface according to the documentation. And, functions are objects too, so that error message could be a little bit confusing.

But the simple answer is: yes, it should be a function.