skip to Main Content

I’m trying to build a simple add to cart container that also happens to toggle between the product sizes.

However i can’t seem to make this work, without writing different functions for each of these buttons.

Here is the JS:

const sizeBtn = document.getElementById("sizebutton");
const sizeBtnTwo = document.getElementById("sizebutton1");
const sizeBtnThree = document.getElementById("sizebutton2");

sizeBtn.addEventListener('click', sizeBtnActive);
sizeBtnTwo.addEventListener('click', sizeBtnActive);
sizeBtnThree.addEventListener('click', sizeBtnActive);

function sizeBtnActive () {
  sizeBtn.classList.toggle('active');
  sizeBtnTwo.classList.toggle('active');
  sizeBtnThree.classList.toggle('active');
}

CSS for context:

.size-btn.faded,
.size-btn.active {
  font-size: 12px;
  color: #c2c2c2;
  background-color: #f0f0f0;
  width: 38px;
  height: 42px;
  border-radius: 0.5rem;
  border: none;
  margin-right: 10px;
  margin-bottom: 35px;
  cursor: none;
}

.size-btn.active {
  color: #ffff;
  background-color: #000000;
  box-shadow: 1px 2px 10px rgba(0, 0, 0, 0.3);
  transition: 1.5s ease;
  cursor: pointer;
}

This code is probably hideous, Your guidance would be appreciated.

I tried googling similar problems of this sort, but none of them as worked thus far. I want to be able to toggle between each buttons without all of them activating at once.

2

Answers


  1. I want to be able to toggle between each buttons without all of them activating at once.

    the shortest way to do that is to first, give all of the buttons one common class name.

    <button class="btn"></button>
    <button class="btn"></button>
    <button class="btn"></button>
    

    then we get those buttons at once using querySelectorAll and do a forEach loop to first disable all of them, and then active the one that is selected:

    const btns = document.querySelectorAll(".btn")
    
    function disableAllButtons() {
        btns.forEach(btn => {
            btn.classList.remove("active")
        })
    }
    
    btns.forEach(btn => {
        btn.addEventListener(() => {
            disableAllButtons()
    
            btn.classList.add("active")
        })
    })
    
    Login or Signup to reply.
  2. You could create a button group that acts like a radio button group.

    Just toggle a data attribute on the active button in the group.

    // Add global button group listener
    window.addEventListener('click', (e) => {
      if (e.target.closest('.button-group')) {
        toggleButtonGroup(e.target);
      }
    });
    
    // Log the new value, after each change
    document.querySelector('.size').addEventListener('click', (e) => {
      setTimeout((buttonGroup) => {
        console.log('Value:', getButonGroupValue(buttonGroup));
      }, 100, e.currentTarget);
    });
    
    // Toggle active state of buttons
    function toggleButtonGroup(button) {
      const buttonGroup = button.closest('.button-group');
      buttonGroup.querySelectorAll('button').forEach((currButton) => {
        if (currButton === button && !currButton.dataset.active) {
          currButton.dataset.active = true;
        } else {
          delete currButton.dataset.active;
        }
      });
    }
    
    // Value accessor
    function getButonGroupValue(buttonGroup) {
      return buttonGroup?.querySelector('[data-active]')?.value;
    }
    .button-group {
      display: inline-flex;
      border: thin solid grey;
      width: fit-content;
    }
    
    .button-group button {
      background: #CCC;
      border: none;
      min-width: 2.5rem;
      padding: 0.25rem;
    }
    
    .button-group button:hover {
      background: #DDA;
      cursor: pointer;
    }
    
    .button-group button[data-active] {
      background: #FFF;
    }
    
    .button-group button[data-active]:hover {
      background: #FFA;
    }
    <label>Size: </label>
    <div class="button-group size">
      <button type="button" value="xs">XS</button>
      <button type="button" value="s">S</button>
      <button type="button" value="m" data-active>M</button>
      <button type="button" value="l">L</button>
      <button type="button" value="xl">XL</button>
      <button type="button" value="xxl">XXL</button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search