dvln dvln - 6 months ago 11
jQuery Question

jquery hide the active accordion content

Im implementing basic jquery accordion, if the accordion content is open, both slide up and slide down actions are performed. It should only hide (slide up) the content div. Need someone's help.

$(document).ready(function() {
$("h3").click(function() {
if ($(".accordion-content").is(":visible")) {
$(".accordion-content").slideUp(600);
$("span.plusminus").text("+");
}
$(this).next(".accordion-content").slideDown(600);
$(this).find("span.plusminus").text("-");
});
});


h3 {
background: #ccc;
padding: 10px;
}
.accordion-content {
display: none;
height: 50px;
}
.plusminus {
float: right;
}


<div class="accordion_container">
<h3>Lorem Ipsum<span class="plusminus">+</span></h3>
<div class="accordion-content">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
</div>
<h3>Lorem Ipsum<span class="plusminus">+</span></h3>
<div class="accordion-content">
<p>Works fine</p>
</div>
<h3>Lorem Ipsum<span class="plusminus">+</span></h3>
<div class="accordion-content">
<p>Works fine</p>
</div>
</div>



Answer

You can do,

$("h3").click(function() {
  if ($(".accordion-content").is(":visible")) {
    $(".accordion-content").not($(this).next()).slideUp(600);
    $("span.plusminus").text("+");

  }
  $(this).next(".accordion-content").slideToggle(600);
  $(this).find("span.plusminus").text("-");
});

Fiddle

  1. Use SlideToggle() for the current cliked element.
  2. USe slideUp() for all the elements except the current one.

Fix for Icon

$("h3").click(function() {
  var icon = $(this).find("span.plusminus");
  $(".accordion-content").not($(this).next()).slideUp(600);
  $("span.plusminus").not(icon).text("+");
  $(this).next(".accordion-content").slideToggle(function() {
    if ($(this).is(":visible")) {
      icon.text("-");
    } else {
      icon.text("+");
    }
  });
});

Edited Fiddle

Comments