0

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

1 Answer 1

2

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");
  });
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is not working. I guess since I removes the active class in the divs, the getElementsByClassName won't be able to find the div because it doesn't have that class initially??
@clanclan I had a couple of typos and forgot to convert an element node list to an array, it should work now jsfiddle.net/bosrLwgy

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.