skip to Main Content

I’m trying to make buttons such that only one is active at a time. But I can’t get it to work.

My HTML:

<button class="js-toggle" onclick="toggle()">Gaming</button>
<button class="js-music-toggle" onclick="toggle2()">Music</button>
<button class="js-tech-toggle" onclick="toggle3()">Tech</button>

My Javascript:

const btnElem = document.querySelector('.js-toggle')
const techBtn = document.querySelector('.js-tech-toggle')
const musicBtn= document.querySelector('.js-music-toggle')

    function toggle() {
      if (!btnElem.classList.contains('is-toggled')) {
        btnElem.classList.add('is-toggled')
      } else {
        btnElem.classList.remove('is-toggled')
      }
      
    }
    
    function toggle2() {
      if (!musicBtn.classList.contains('is-toggled')) {
        musicBtn.classList.add('is-toggled')
      } else {
        musicBtn.classList.remove('is-toggled')
      }
    }
    
    function toggle3() {
      if (!techBtn.classList.contains('is-toggled')) {
        techBtn.classList.add('is-toggled')
      } else {
        techBtn.classList.remove('is-toggled')
      }
    }

2

Answers


  1. Please use this code:

    Code:

    HTML:

    <div class="button-container">
    <button class="js-toggle">Gaming</button>
    <button class="js-music-toggle">Music</button>
    <button class="js-tech-toggle">Tech</button>
    </div>
    

    JavaScript:

    const buttonContainer = document.querySelector('.button-container')
    const buttons = buttonContainer.querySelectorAll('button')
    
    buttonContainer.addEventListener('click', e => {
    if (e.target.tagName === 'BUTTON') {
    buttons.forEach(button => {
    if (button !== e.target) {
    button.classList.remove('is-toggled')
    }
    })
    e.target.classList.toggle('is-toggled')
    }
    })
    
    Login or Signup to reply.
  2. Try this,

    function toggle(btnElem) {
        if (!btnElem.classList.contains('is-toggled')) {
          document.querySelectorAll(".is-toggled").forEach(btn => btn.classList.remove('is-toggled'));
          btnElem.classList.add('is-toggled');
          return;
        } 
        btnElem.classList.remove('is-toggled')
    }
        
    .is-toggled {
      color:red;
      font-weight: bold;
      letter-spacing: 1px;
    }
    <button class="js-toggle" onclick="toggle(this)">Gaming</button>
    <button class="js-music-toggle" onclick="toggle(this)">Music</button>
    <button class="js-tech-toggle" onclick="toggle(this)">Tech</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search