clanclan
clanclan

Reputation: 3

How to select a div element with JavaScript and change background color?

So, on my website I have a pop-up modal that contains a form. The form has 5 divs that contain a picture and a description. I found the following JS code on w3schools that enables me to select a div and give it the styling I want. However, when I first open the modal, one div is selected. But I don't want any to be selected. I am not sure how to modify this code to make it so no divs are seleced initially.

      // When user clicks an div, add background
      var divs = document.getElementsByClassName("mood-state");
      for (var i = 0; i < divs.length; i++) {
        divs[i].addEventListener("click", function () {
          var current = document.getElementsByClassName("active");
          current[0].className = current[0].className.replace(" active", "");
          this.className += " active";
        });
      }

Here is some of the div in the modal

            <div class="mood-state">
              <img src="neutral.svg" alt="" />
              <p>Neutral</p>
            </div>
            <div class="mood-state">
              <img src="smile.svg" alt="" />
              <p>Pleasant</p>
            </div>
            <div class="mood-state active">
              <img src="grin.svg" alt="" />
              <p>Very Pleasant</p>
            </div

Upvotes: 0

Views: 414

Answers (1)

Samathingamajig
Samathingamajig

Reputation: 13245

Remove the active class in the HTML. Having that there makes it initially start as active.

<div class="mood-state active"> <-- You have the active class here
  <img src="grin.svg" alt="" />
  <p>Very Pleasant</p>
</div>

Change that to

<div class="mood-state"> <-- No 'active' class here
  <img src="grin.svg" alt="" />
  <p>Very Pleasant</p>
</div>

You also need to change your JavaScript to fix a bug

// When user clicks an div, add background
var divs = document.getElementsByClassName("mood-state");
for (var i = 0; i < divs.length; i++) {
  divs[i].addEventListener("click", function() {
    [...document.getElementsByClassName("active")].forEach(ele => ele.classList.remove("active"));
    this.classList.add("active");
  });
}

Upvotes: 2

Related Questions