Dan Knights
Dan Knights

Reputation: 8368

Toggle current element in jQuery

I have a div filled with 'card' elements: Home page filled with cards

When I click on one, the descriptions for all of them are toggled using jQuery: cards with description displayed

I've managed to make it so that once the descriptions appear, if you click on the card, only the individual cards description is toggled back while the rest remain: enter image description here

How can I also make the descriptions appear for only the individual card being clicked, not all of them at the same time?

jQuery:

  $('.front .description, .front img').click(() => {
    $('.back').show('fade');
  })

  $('.back').click((e) => {
    $(e.currentTarget).hide('fade');
  })

HTML:

<div class="card">
  <div class="front">
    <img src="../img/card.png" alt="magic the gathering playing card" />
    <div class="description">
      <p>Black Lotus</p>
      <p>£1000</p>
    </div>
    <button>Add to cart</button>
  </div>
  <div class="back">
    <p>
      Necessitatibus sint earum temporibus consequatur quasi cum magnam aut
      sequi voluptate natus perferendis, illo ipsum voluptatem, saepe modi,
      ullam omnis consectetur eos sed iure non. Voluptate, molestias.
    </p>
  </div>
</div>

Not sure how to implement e.currentTarget in this context. Any help would be greatly appreciated.

Upvotes: 1

Views: 230

Answers (2)

Mamun
Mamun

Reputation: 68923

You can use Event.target to find the closest() card, then find() the specific .back

$('.front .description, .front img').click((e) => {
  $(e.target).closest('.card').find('.back').show('fade');
})

OR: You can use this keyword with normal function syntax (not arrow function):

$('.front .description, .front img').click(function() {
  $(this).closest('.card').find('.back').show('fade');
});

Upvotes: 3

Abdelrahman Gobarah
Abdelrahman Gobarah

Reputation: 1589

try this code

$('.front .description, .front img').click(() => {
    $(this).parents('.card:first').find('.back').show('fade'); // this line
  })

  $('.back').click((e) => {
    $(e.currentTarget).hide('fade');
  })

Upvotes: 0

Related Questions