Question

I'm having trouble figuring out a bug in my accordion. The arrow icons are misbehaving when clicked on. If you go here, you will see some categories hidden by accordions. When you click on one and then close it, it behaves properly. But if you click on one, then click on another below before closing the first one, you'll notice that the arrow for the one above has returned to its "closed" position without closing it.

Here is the HTML that makes up each accordion:

<dl class="accordion">
<dt><strong>Accordion Title:</strong>&nbsp;&nbsp;Details</dt>
<dd>Hidden details</dd>
</dl>

The CSS for the arrows:

.accordion dt:after {
  content: "\f125";
  color: #ED4F30;
  font-family: "Ionicons";
  padding-left: 10px;
}

and

.accordion dt.accordion-active:after {
  content: "\f123";
  color: #ED4F30;
  font-family: "Ionicons";
  padding-left: 10px;
}

And finally the jQuery that I'm using to expand/collapse:

function ($) {
  //Hide all panels
    var allPanels = $('.accordion > dd').hide();
  //Show first panel
  //$('.accordion > dd:first-of-type').show();
  //Add active class to first panel 
  //$('.accordion > dt:first-of-type').addClass('accordion-active');
  //Handle click function
    jQuery('.accordion > dt').on('click', function () {
      var $this = $(this) ,
          $target = $this.next();
           jQuery('.accordion > dt.accordion-active').not($this.toggleClass('accordion-active')).removeClass('accordion-active');
      $this.siblings('dd').not($target.addClass('active').slideToggle()).slideUp();
      return false;
    });
}

Any ideas what I'm missing?

Was it helpful?

Solution

It looks like you are overcomplicating things a little. You don't need to use the "not()" method to filter anything out. You are only toggling between 2 states (add/remove class, show/hide element) so you only need to use 2 jQuery methods, which were already in your code.

jQuery('.accordion > dt').on('click', function () {
    var $this = $(this),
        $target = $this.next();
    $this.toggleClass('accordion-active');
    $target.slideToggle();
    return false;
});

Here's a JSFiddle based on the code you provided: http://jsfiddle.net/e5pe5/

Let me know if this is the intended functionality of your accordion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top