0

enter image description here[Picture of boxes]: https://i.stack.imgur.com/X018k.png

As shown in the image I have three boxes. What I want to do is when I click a box it turns the background-color green, then when I click it again it goes back to its original state. The code I have works, but is there a more efficient way of writing the JavaScript?

HTML

 <div class="container">
      <div class="box first"></div>
      <div class="box second"></div>
      <div class="box third"></div>
    </div>

CSS

.colors {
  background: green;
}

JavaScript

const first = document.querySelector(".first");
const second = document.querySelector(".second");
const third = document.querySelector(".third");

first.addEventListener("click", () => {
  first.classList.toggle("colors");
});

second.addEventListener("click", () => {
  second.classList.toggle("colors");
});

third.addEventListener("click", () => {
  third.classList.toggle("colors");
});
zcode97
  • 13
  • 2
  • 3
    Yes, [delegate](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation) a single event to `.container`, and use event object passed to the handler function to recognize the clicked target element. – Teemu Nov 16 '22 at 05:37
  • Or use a checkbox so that you won't need javascript at all. – vighnesh153 Nov 16 '22 at 05:39

0 Answers0