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
the shortest way to do that is to first, give all of the buttons one common class name.
then we get those buttons at once using
querySelectorAll
and do aforEach
loop to first disable all of them, and then active the one that is selected: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.