Lepros
Lepros

Reputation: 19

How to remove class only after the first click?

The user is to choose a rating of 1-5 by clicking on one of the numbers. If the user has already clicked a number, and then they click a different number, I want the original number to be deselected with the new number is clicked. So far, I am only able to make it work if the user manually clicks on the first number a second time (otherwise two numbers are selected at the same time). I don't want them to have to do that.

This is what I have so far, but it's not what I want since it requires a manual deselection if the user changes their mind after first click:

const choices = document.querySelectorAll(".choice");

choices.forEach(choice => {
  choice.addEventListener("click", function handleClick(event) {
    choice.classList.toggle("choice-active");
  });
});

Upvotes: 0

Views: 51

Answers (1)

Abdul Basit
Abdul Basit

Reputation: 450

You have to Remove All Choices Active Class Before Adding Class to Clicked Choice like below Example:

const choices = document.querySelectorAll(".choice");

choices.forEach(choice => {
  choice.addEventListener("click", function handleClick(event) {
    // Removing All Choice Active Class Except Clicked One
    choices.forEach(ch => {
      
      // Skip If Current Choice is Clicked Choice
      if (ch === choice) {
        return;
      }
      
      // Removing Active Class
      ch.classList.remove("choice-active");
    });
    
    // Toggle Active Class of Clicked Choice    
    choice.classList.toggle("choice-active");
  });
});
ul {
  text-decoration: none;
  list-style-type: none;
  padding: 0px;
}

li.choice {
  cursor: pointer;
  display: inline;
  background: #f3f3f3;
  padding: 10px;
  border: 1px solid white;
}

li.choice-active {
  background: red;
}
<ul>
  <li class="choice">
    1
  </li>
  <li class="choice">
    2
  </li>
  <li class="choice">
    3
  </li>
  <li class="choice">
    4
  </li>
  <li class="choice">
    5
  </li>
</ul>

Upvotes: 2

Related Questions