On my website, I have 3 buttons that represent different product categories. The initial state of the page should load with the "All Products" button having an active class. However, when clicked, this active class should be removed from the "All Products" button and added to another button. Unfortunately, there seems to be a glitch causing the active class to either be added twice to a button or not removed at all, resulting in two buttons being active simultaneously. Seeing Two Active Buttons? and Experiencing Duplicate Active Classes?
To solve this issue, I can remove the active class from the "All Products" button entirely, but ideally, I want it to be initially set as active when the page loads. These buttons also need to toggle visibility for elements based on the category they belong to.
Below is the code snippet:
HTML:
<div class="list-group" id="myBtnContainer">
<button class="btn list-group-item active" onclick="filterSelection('all')">All Products</button>
<button class="btn list-group-item" onclick="filterSelection('shirts')">Shirts</button>
<button class="btn list-group-item" onclick="filterSelection('pants')">Pants</button>
</div>
Example HTML Element:
<div class="col-lg-4 col-md-6 mb-4 filterDiv shirts">
<div class="card h-100 ">
<a href="product.html"><img class="card-img-top" src="blackshirt.png" alt=""></a>
<div class="card-body">
<h4 class="card-title">
<a href="product.html" class="product-title">Black Shirt</a>
</h4>
<h5>$24.99</h5>
<p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur!</p>
</div>
<div class="card-footer">
<a href="product.html" class="btn btn-success view-btn" role="button"><i class="fa fa-search"></i> View Product</a>
</div>
</div>
</div>
JavaScript
filterSelection("all")
function filterSelection(c) {
var x, i;
x = document.getElementsByClassName("filterDiv");
if (c == "all") c = "";
for (i = 0; i < x.length; i++) {
w3RemoveClass(x[i], "show");
if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
}
}
function w3AddClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
if (arr1.indexOf(arr2[i]) == -1) {element.className += " " + arr2[i];}
}
}
function w3RemoveClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
while (arr1.indexOf(arr2[i]) > -1) {
arr1.splice(arr1.indexOf(arr2[i]), 1);
}
}
element.className = arr1.join(" ");
}
// Add active class to the current button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function(){
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}