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 DOM Scripting By Example Adding and Removing Names Practice with Function Scope

Thomas H
seal-mask
.a{fill-rule:evenodd;}techdegree
Thomas H
Full Stack JavaScript Techdegree Student 4,545 Points

practice with function scope

Hi coders !

I'm stuck with this exercise and i dont get exactly how to change the event refering to a outside scope.

Im looking for more on courses,but can you give me a hint ?

Thank you

app.js
const redButton = document.getElementById('redButton');
const blueButton = document.getElementById('blueButton');

redButton.addEventListener('click', (e) => {
  const colorSquare = document.getElementById('colorDiv');
  colorSquare.style.backgroundColor = 'red';
});

blueButton.addEventListener('click', (e) => {
  blueButton.style.backgroundColor = 'blue';
})
style.css
div {
  height: 50px;
  float: left;
  padding-top: 40px;
  padding-left: 20px;

}

#colorDiv {
  padding: 0;
  width: 100px;
  height: 100px;
  background-color: gray;
}

button {
  height: 30px;
  border-radius: 10px;
}
#redButton {
  background-color: #ff5959;
  border-color: red;
}

#blueButton {
  background-color: lightblue;
  border-color: #7C9EFC;
}

2 Answers

Steven Parker
Steven Parker
230,274 Points

The red button is working because it defines "colorSquare", but since the definition is limited to its own scope, it can't be accessed from the blue button handler.

But if you move that line of code outside of the function, and put it with the other global declarations at the top, it will be be accessible by both handler functions.