skip to Main Content

I have two buttons inside my video projects, "Pause" and "Play" and looking for a special color effect to be applied on the current active button only, but clicking the current button couldn’t remove the color effect on the button which was clicked before.

The target is for the special color effect to be applied interchangeably. What line of code did I miss here?

const btns = document.querySelectorAll(".switch-btn");

btns.forEach((btn) => {
      btn.addEventListener("click", function(event) {
        const currentBtn = event.currentTarget;

        if (!currentBtn.classList.contains("active")) {
          currentBtn.classList.add("active")
        } else {
          currentBtn.classList.remove("active")
        }

      })
<div class="btns">
  <button class="switch-btn" data-control="pause">Pause</button>
  <button class="switch-btn" data-control="play"> Play</button>
</div>

2

Answers


  1. First, remove the ‘active’ class from all buttons, Then add the ‘active’ class only to the clicked button, Just add the HTML, CSS and JS sequencing as per your HTML code:

    const btns = document.querySelectorAll(".switch-btn");
    
    btns.forEach((btn) => {
      btn.addEventListener("click", function(event) {
        btns.forEach(button => {
          button.classList.remove("active");
        });
    
        event.currentTarget.classList.add("active");
      });
    });
    .switch-btn {
      padding: 10px 20px;
      margin: 5px;
      cursor: pointer;
    }
    
    .switch-btn.active {
      background-color: #f5c453;
      color: white;
    }
    <div class="btns">
      <button class="switch-btn" data-control="pause">Pause</button>
      <button class="switch-btn" data-control="play">Play</button>
    </div>
    Login or Signup to reply.
  2. const btns = document.querySelectorAll(".switch-btn");
    
    // to add event listener on each button
    btns.forEach(btn => {
      btn.addEventListener('click', (e) => {
        // to remove btn-active class from each button
        btns.forEach(btn => btn.classList.remove('btn-active'));
        
        // apply class active on current target
        e.target.classList.add('btn-active');
      });
    });
    .switch-btn {
      background: #CCC;
      padding: 7px 14px;
      color: #000;
      border: 0;
      border-radius: 5px;
      cursor: pointer;
    }
    
    .switch-btn:hover,
    .btn-active {
      color: #FFF;
      background: #00F;
    }
    <div class="btns">
      <button class="switch-btn" data-control="pause">Pause</button>
      <button class="switch-btn" data-control="play"> Play</button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search