JavaScript DOM Scripting By Example Adding and Removing Names Practice with Function Scope

michael edmondson
michael edmondson
2,590 Points

Challenge

Not sure what i should do with the const color square should i remove it from the event handler or put it at the top of the page and not sure what i should do with the red button and blue button. should i turn them into if statments?

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) => {
const colorSquare = document.getElementById('colorDiv');
colorSquare.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;
}

1 Answer

Fernando Boza
Fernando Boza
24,154 Points

michael edmondson you're right with your first instinct. to keep it DRY you just need to remove

  const colorSquare = document.getElementById('colorDiv');

from red button eventlistner function and make it "global" so both event listeners can access and modify it.

const redButton = document.getElementById('redButton');
const blueButton = document.getElementById('blueButton');
const colorSquare = document.getElementById('colorDiv'); // moved it up here

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

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