Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle CSS class with jQuery [duplicate]

I can't seem to get this to work. What I want to do is have jQuery add / remove (or toggle) a class which has display:none on it

jQuery

  <script type ="text/javascript">

    //Event Triggers
    $("#cbVitamins").click(function(evt){
      $("#products h2.product-type[data-type=vitamin]").parent().addClass("hideItem");
    });
  </script>

CSS

  <style>
    .hideItem {
      display:none;
    }
  </style>

HTML Button to hook event onto

      <div>
        <span>Show: </span>
        <input id="cbVitamins" type="checkbox" checked="checked"/>
        <label for="cbVitamins">Vitamins</label>
      </div>

HTML → add .hideItem class to the li element

<li class="product-item" data-prod_id="V-C6614">
    <img class="product-image" src="images/products/vitamin-c.jpg" alt="Vitamin C - Product Photo">
    <h2 class="product-name" data-type="vitamin">Vitamin C</h2>
</li>

what its supposed to do:

enter image description here

like image 757
Vincent Tang Avatar asked Jan 29 '23 20:01

Vincent Tang


1 Answers

The problem is that you're targeting the class product-type with your jQuery, when you're actually using the class product-name in your HTML.

You can toggle visibility with the .toggle() method -- you don't need to create a separate class:

//Event Triggers
$("#cbVitamins").click(function(evt) {
  $("h2.product-name[data-type=vitamin]").parent().toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <span>Show: </span>
  <input id="cbVitamins" type="checkbox" checked="checked" />
  <label for="cbVitamins">Vitamins</label>
</div>

<li class="product-item" data-prod_id="V-C6614">
  <img class="product-image" src="images/products/vitamin-c.jpg" alt="Vitamin C - Product Photo">
  <h2 class="product-name" data-type="vitamin">Vitamin C</h2>
</li>

Hope this helps! :)

like image 155
Obsidian Age Avatar answered Feb 03 '23 03:02

Obsidian Age