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

Even the background was becoming red. The question seems wrong.

When checking the preview mode, the background is becoming red on click. Why my code is wrong?

app.js
const warning = document.getElementById("warning");
let button = document.getElementById('makeItRed');
button.addEventListener('click', () => {
    document.body.style.backgroundColor = "red";
});
index.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>

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! I received your request for assistance. The reason your entire document is becoming red, is very simply because you told it to :smiley: Hang with me and I'll show you what I mean.

In this line, you are telling the code to turn everything in the <body> tags red:

 document.body.style.backgroundColor = "red";

Note the "body" part of the previous line. This selects the body portion of the document and turns the background color red. Which is the entire viewable portion of the document. You were only meant to turn the div with the id of "warning" red. Luckily, you set up a const in the very first line of the code that selects that particular div.

So instead of selecting the body and assigning red, it should be:

 warning.style.backgroundColor = "red";

Here, we use the variable/constant that holds the div with the id of "warning" and we set its background color to red.

Hope this helps! :sparkles:

I figured it out. I had to assign it to the div.

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

Is the right answer.