blicht454
blicht454

Reputation: 29

Display next div only and hide other divs with same class

Many versions of this question have already been asked but I can't seem to find a solution.

I'm hoping to have just one div visible at a time and to toggle an 'open' class on the correct trigger.

Here's what I have so far:

<div class="wrap">
    <div class="trigger"></div>
    <div class="description">
        <p>Here's a description</p>
    </div>
</div>
<div class="wrap">
    <div class="trigger"></div>
    <div class="description">
        <p>Here's a description</p>
    </div>
</div>
<div class="wrap">
    <div class="trigger"></div>
    <div class="description">
        <p>Here's a description</p>
    </div>
</div>

And the jQuery:

$(function () {
    $(".trigger").click(function (e) {
      e.preventDefault();
      $(this).next('.description').fadeToggle('fast');$(this).toggleClass('open');
    });
});

And that works to get the proper div opened and closed, but what I'm hoping for is some logic to make any other 'description' divs close so only one will be open at a time.

Any help would be much appreciated!

Upvotes: 1

Views: 2156

Answers (2)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try to hide all .description except the current element's linked .description,

  $(function () {
     $(".trigger").click(function (e) {
      e.preventDefault();
      $(".description").not($(this).toggleClass('open').next('.description').fadeToggle("slow")).fadeOut('fast');
     });
  });

DEMO

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You need to hide the sibling elements like

$(function() {
  $(".trigger").click(function(e) {
    e.preventDefault();
    $(this).toggleClass('open').siblings('.trigger').removeClass('open');
    $(this).next('.description').stop().fadeToggle('fast').siblings('.description').stop().fadeOut('fast');
  });
});
.description {
  display: none;
}
.open {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="trigger">t1</div>
<div class="description">
  <p>Here's a description</p>
</div>
<div class="trigger">t2</div>
<div class="description">
  <p>Here's a description</p>
</div>
<div class="trigger">t3</div>
<div class="description">
  <p>Here's a description</p>
</div>

Upvotes: 0

Related Questions