Skip to content Skip to sidebar Skip to footer

Removing Active Class From Button

I have 3 buttons that represent a product category on my site. I want to load the page with the 'All Products' button having an active class and then have that class removed and ad

Solution 1:

  • Two active buttons at once

    Check the logic within this function filterSelection.

  • Active class added twice

    You can use toggle function from the classList attribute.

  • Show products according to the selected button

    • Use the data attributes and work with the classList attribute.
    • I.e: Set to your buttons: data-target='shirts', data-target='pants' and so on.
    • Use a class hide with this style: display: none

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].classList.toggle('active');
    this.classList.toggle('active');
    
    var target = this.dataset.target;
    filterSelection(target);
  });
}

functionfilterSelection(target) {
  document.querySelectorAll('.filterDiv').forEach((div) => {
    if (target === 'all' || div.classList.contains(target)) {
      div.classList.remove('hide');
    } else {
      div.classList.add('hide');
    }
  });
}
.active {
  background-color: lightgreen;
}

.hide {
  display: none
}
<divclass="list-group"id="myBtnContainer"><buttonclass="btn list-group-item active"data-target='all'>Show all</button><buttonclass="btn list-group-item"data-target='shirts'>Shirts</button><buttonclass="btn list-group-item"data-target='pants'>Pants</button></div><divclass="col-lg-4 col-md-6 mb-4 filterDiv shirts"><divclass="card h-100 "><ahref="product.html"><imgclass="card-img-top"src="blackshirt.png"alt=""></a><divclass="card-body"><h4class="card-title"><ahref="product.html"class="product-title">Black Shirt</a></h4><h5>$24.99</h5><pclass="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur!</p></div><divclass="card-footer"><ahref="product.html"class="btn btn-success view-btn"role="button"><iclass="fa fa-search"></i> View Product</a></div></div></div><divclass="col-lg-4 col-md-6 mb-4 filterDiv pants"><divclass="card h-100 "><ahref="product.html"><imgclass="card-img-top"src="blackshirt.png"alt=""></a><divclass="card-body"><h4class="card-title"><ahref="product.html"class="product-title">Pants</a></h4><h5>$44.99</h5><pclass="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur!</p></div><divclass="card-footer"><ahref="product.html"class="btn btn-success view-btn"role="button"><iclass="fa fa-search"></i> View Product</a></div></div></div>

Resource

Post a Comment for "Removing Active Class From Button"