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

How to alter the javascript code without adding any lines to the blue button's event handler?

Shouldn't this work? I am simply taking the code and using it in a if else statement. Although not specifically what the challenge asks for but I still think it should work this way if needed.

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

redButton.addEventListener('click', (e) => {
  const colorSquare = document.getElementById('colorDiv');
  if (e.target.tagName === 'redButton') {
      colorSquare.style.backgroundColor = 'red';
      } else if (e.target.tagName === 'blueButton') {
        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

Steven Parker
Steven Parker
229,786 Points

This doesn't work for the red button because "redButton" is being compared with the tagName when it is actually the id.

And it won't work on the blue button even after fixing the id reference because the handler is only being attached directly to the red button.

But you could make it a delegated handler for both by attaching it to a common parent (like the body) instead:

document.body.addEventListener("click", e => {
  const colorSquare = document.getElementById("colorDiv");
  if (e.target.id === "redButton") {
    colorSquare.style.backgroundColor = "red";
  } else if (e.target.id === "blueButton") {
    colorSquare.style.backgroundColor = "blue";
  }
});