hendy0817
hendy0817

Reputation: 1079

Hide/show elements with same class on click

I'm trying to have some text toggle on click of elements with same class. I have the text showing on click but when I click another element the text remains. How do I have it removed from others when another element of same class is clicked?

$('.video-carousel--thumbnail').on('click', function() {
  $(this).find('.now-playing').not(this).css('display', 'none');
  $(this).find('.now-playing').css('display', 'block');
});
.now-playing {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="video-carousel--thumbnail">
  <div class="l-thumbnail__title">
    <p><strong>Thumbnail One</strong></p>
    <p class="now-playing"><strong>Now Playing</strong></p>
  </div>
</div>
<div class="video-carousel--thumbnail">
  <div class="l-thumbnail__title">
    <p><strong>Thumbnail Two</strong></p>
    <p class="now-playing"><strong>Now Playing</strong></p>
  </div>
</div>
<div class="video-carousel--thumbnail">
  <div class="l-thumbnail__title">
    <p><strong>Thumbnail Three</strong></p>
    <p class="now-playing"><strong>Now Playing</strong></p>
  </div>
</div>

Upvotes: 0

Views: 646

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337743

You don't need the DOM traversal logic when hiding all other elements. Just select them directly using $('.now-playing'). Also note that you can use hide() and show() instead of css().

$('.video-carousel--thumbnail').on('click', function() {
  $('.now-playing').hide()
  $(this).find('.now-playing').show();
});

Also note that if you want to toggle the elements then your not() selector is incorrect as this refers to the .video-carousel--thumbnail element which raised the event, not the .now-playing element to exclude from the collection.

For that to work you need to find the relevant element first, then exclude it from those you remove the class from before calling toggle(). Try this:

$('.video-carousel--thumbnail').on('click', function() {
  var $target = $(this).find('.now-playing');
  $('.now-playing').not($target).hide()
  $target.toggle();
});
.now-playing {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="video-carousel--thumbnail">
  <div class="l-thumbnail__title">
    <p><strong>Thumbnail One</strong></p>
    <p class="now-playing"><strong>Now Playing</strong></p>
  </div>
</div>
<div class="video-carousel--thumbnail">
  <div class="l-thumbnail__title">
    <p><strong>Thumbnail Two</strong></p>
    <p class="now-playing"><strong>Now Playing</strong></p>
  </div>
</div>
<div class="video-carousel--thumbnail">
  <div class="l-thumbnail__title">
    <p><strong>Thumbnail Three</strong></p>
    <p class="now-playing"><strong>Now Playing</strong></p>
  </div>
</div>

Upvotes: 1

Related Questions