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 Adding an Event Listener

This kind of thing is really maddening as a student. When a solution works but is rejected.

Here is an example of one of the challenges:

Challenge Task 3 of 3 In the button click handler apply the background color of "red" to the warning div.

Here is the HTML

<!DOCTYPE html>
<html>
    <head>
        <title>Adding an Event Listener</title>
    </head>
    <link rel="stylesheet" href="style.css" />
    <body>
        <div id="warning">
            Warning: My background should be red!
        </div>
        <button id="makeItRed">Make It Red!</button>
        <script src="app.js"></script>
    </body>
</html>

Here is the Javascript I offered as a solution:

const warning = document.getElementById("warning");
let button = document.getElementById("makeItRed");
button.addEventListener('click', () => {
  document.getElementById('warning').style="background-color: red";
});

I hope this screenshot of what happened when I clicked the โ€œPreviewโ€ button works because it clearly shows that the solution worked.

Unfortunately the screenshot doesn't work. However before the button in clicked the background is white. After it is clicked the background is red.

Here is what I got when I clicked โ€œRecheck Workโ€.

Bummer! When the button is clicked the background doesn't turn red.

Anyone got any idea about what is up with this?

2 Answers

The real answer is this, Scott went part of the way. The reason my first goto failed was syntax:

button.addEventListener('click', () => {
  warning.style.backgroundColor ="red";
});

You're creating a variable called "warning" but never using it. In your event listener, try referencing the warning variable you've already created rather than doing the work a second time to the find the element with an ID of "warning".

Scott:

I appreciate the input. This was my first go to.

button.addEventListener('click', () => {
  warning.style="background-color: red";
});

The reason I abandoned it was because it didn't work. Now, I'll admit I often miss subtleties, so there may be something else that is wrong. The only thing I can think of is scope, but I would expect that to give me an undefined variable on warning.