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

Philip Valentini
Philip Valentini
3,448 Points

Can anyone help with this problem please?

I think I need to add a function in the blueButton portion of the code starting in line 9...but I can seem t get it to work....Im sure i'm doing something wrong here.
Any assistance would be great.

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';
});

function makeBlue(colorDiv) {
  colorSquare.style.backgroundColor = 'blue';
  return 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

Hi,

I guess the challenge asks you to not modify the blueButton's event listener.

So you can just leave it as:

blueButton.addEventListener('click', (e) => {
  colorSquare.style.backgroundColor = 'blue';
});

However, doing this the redButton event listener is not working because the variable colorSquare can't be accessed since it only exists in the scope of the redButton's event listener. That is easy to fix though. Modify the event listener of the red button in a way that will make the colorSquare variable accessible to both event listeners.

const redButton = document.getElementById('redButton');
const blueButton = document.getElementById('blueButton');
const colorSquare = document.getElementById('colorDiv'); //by moving it into the global scope, both event listeners have access to it

redButton.addEventListener('click', (e) => {
  // Move this into the global scope const colorSquare = document.getElementById('colorDiv');
  colorSquare.style.backgroundColor = 'red';
});

blueButton.addEventListener('click', (e) => {
 colorSquare.style.backgroundColor = 'blue';
}
Philip Valentini
Philip Valentini
3,448 Points

Wow! Thank you! and than you for the comments as well this makes sense and i get now. Much appreciated Alexander!