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 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,677 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.