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) The Browser Environment Thinking Globally

Tomasz Cysewski
Tomasz Cysewski
2,736 Points

Program in console: on click change color of myHeading

Hello, I want to create a program that changes background color of myHeading on click, how to make it work properly?

var myheading = document.getElementById('myHeading');
myheading.addEventListener('click', myheading.backgroundColor = 'black');

1 Answer

Anthony McCormick
Anthony McCormick
6,774 Points

Below should work, this creates an anonymous function inside the event listener.

var myheading = document.getElementById('myHeading');
myheading.addEventListener('click', function() {
    myheading.style.backgroundColor = 'black';
});
Tomasz Cysewski
Tomasz Cysewski
2,736 Points

ok, but why function? is eventlistener only accepting functions?

Tomasz Cysewski
Tomasz Cysewski
2,736 Points

ok, but why function? is eventlistener only accepting functions?

Anthony McCormick
Anthony McCormick
6,774 Points

As far as I am aware, the eventListener only accepts a function but this can be defined anonymously such as my example above or created somewhere else in your script file.

Further reading: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener