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

aliceinwonderland
aliceinwonderland
7,679 Points

I'm not sure I understand the question. Here is my code. It is wrong.

Perhaps I don't understand the question?

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

Could you link the question please.

there's a link to the relevant challenge to the right of the breadcrumbs

Ah yes my apologies I didn't see that :D

3 Answers

aliceinwonderland
aliceinwonderland
7,679 Points

i know the func structure wasn't the problem. i was just explaining how i see the difference between the two ways to write a function after charlie showed the alternative way. i think he was just giving some more material to learn after my error was solved by you, adam.

There is also another way of doing this code for the last two lines:

So instead of:

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

It could be:

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

Happy coding :)

aliceinwonderland
aliceinwonderland
7,679 Points

thank you so much. i see the fat arrow way is not much different--you just omit the word "function" and insert a fat arrow between the parentheses and the opening bracket.

The structure of your func was not the problem w/ your code.

It was just an alternative way of doing it. You had already answered the question It's just nice to know that there are two answers to the question.

:)

The proper syntax to change the styling of an element using vanilla js is:

element.style.cssProperty = 'whatever'

Let me know if this helps here

aliceinwonderland
aliceinwonderland
7,679 Points

thank you, adam. i forgot the .style part!