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 trialTomasz Cysewski
2,736 PointsProgram 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
6,774 PointsBelow 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
2,736 PointsTomasz Cysewski
2,736 Pointsok, but why function? is eventlistener only accepting functions?
Tomasz Cysewski
2,736 PointsTomasz Cysewski
2,736 Pointsok, but why function? is eventlistener only accepting functions?
Anthony McCormick
6,774 PointsAnthony McCormick
6,774 PointsAs 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