How do I use jQuery toggle class to add class or remove element?

Viewed 118

I'm not sure why my code is not responding, everything looks correct to me. I'm new to using jQuery and trying to use toggleClass to have card info displayed when the card on my page is clicked. Initially, I'd like it to be hidden but able to be toggled on and off.

$(document).ready(function() {
  $('.card').click(function() {
    $(this).toggleClass('inner-card.active');
  });
});
.card {
  display: flex;
  flex-direction: column;
  justify-content: end;
  width: 350px;
  height: 180px;
  background: lightgreen;
  border: 2px solid black;
  margin-left: 8px;
  margin-bottom: 8px;
  cursor: pointer;
}

.inner-card .active {
  display: none;
}

.inner-card {
  display: flex;
  flex-direction: column;
  justify-content: end;
  background: rgba(255, 165, 0, 0.5)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
  <div class="inner-card">
    <h5>Title</h5>
    <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Sunt, libero?</p>
    <a href="">Link goes here</a>
    <div class="img-div">
      <img src="../static/img/search.png" class="card-img" alt="">
    </div>
  </div>
</div>

It should go from this

enter image description here

To this

enter image description here

2 Answers

I believe there are several problems. First of all, I believe you want to write the display:none CSS logic this way:

.inner-card.active{
    display: none;
} 

This means that the inner card will be hidden if it also has the active class.

Secondly, I believe you need to rewrite the script this way:

 $(document).ready( function(){
     $('.card').click( function() {
         $(this).find(".inner-card").toggleClass('active');
     });
 });

When you use the toggleClass you need to use just the name of the class, not the selector (-> no dot). Also, from the CSS, it looks like you need to find the inner card element first.

Fiddle link

You probably want something like this:

$(document).ready(function() {
  $('.card').click(function() {
    $(this).find(".inner-card").toggleClass('hidden');
  });
});
.card {
  display: flex;
  flex-direction: column;
  justify-content: end;
  width: 350px;
  height: 180px;
  background: lightgreen;
  border: 2px solid black;
  margin-left: 8px;
  margin-bottom: 8px;
  cursor: pointer;
}

.hidden {
  display: none !important;
}

.inner-card {
  display: flex;
  flex-direction: column;
  justify-content: end;
  background: rgba(255, 165, 0, 0.5)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
  <div class="inner-card hidden">
    <h5>Title</h5>
    <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Sunt, libero?</p>
    <a href="">Link goes here</a>
    <div class="img-div">
      <img src="../static/img/search.png" class="card-img" alt="magnify lens">
    </div>
  </div>
</div>

Related