bjorkland bjorkland - 3 months ago 6
jQuery Question

toggleClass not closing div once opened

I have some really simple lines of jQuery that are meant to open and close a div when clicking a link. When I click, the div opens fine (and any other open div, will close, which is good). But, when I click the link again the div will not close! I cannot figure out why. Any help would be much appreciated!

HTML:

<a href="../partial-2" id="products">
<div class="products">
<p>products</p>
</div>
</a>
<div class="row product-options products-house shadow">
<div class="col-sm-6 col-sm-offset-3">
....content here, removed for brevity....
</div>
</div>


jQuery:

$(document).ready(function(){
$("#products").on("click", function(e){
e.preventDefault();
$(".active-product").removeClass("active-product");
$(".products-house.shadow").toggleClass("active-product");
});


In my CSS, I just have a display:none for the products-option, and display: block for active-product

Answer

While removing the class exclude the .products-house.shadow element using :not() pseudo-class selector.

$(document).ready(function(){
   $("#products").on("click", function(e){
     e.preventDefault();
     $(".active-product:not(.products-house.shadow)").removeClass("active-product");
     //        --------^^^^----------------------^^^^------
     $(".products-house.shadow").toggleClass("active-product");
});