How to make accordion active item clickable

After trial-and-erroring for the last couple hours, I realize I should really take a course on the basics of jQuery. Can someone help me with what will likely be a simple answer?

I am putting this accordion into a page, but I want the active panel to be able to click to close. Is there something simple I can do to make it possible?

(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() {

    //this clicked panel
    $this = $(this);

    //the target panel content
    $target = $this.next();

    //Only toggle non-displayed 
    if(!$this.hasClass('accordion-active')){

      //slide up any open panels and remove active class
      $this.parent().children('dd').slideUp();

      //remove any active class
      jQuery('.accordion > dt').removeClass('accordion-active');

      //add active class
      $this.addClass('accordion-active');

      //slide down target panel
      $target.addClass('active').slideDown();

    }

    return false;
  });

})(jQuery);

Related posts

Leave a Reply

1 comment

  1. Try:

      jQuery('.accordion > dt').on('click', function() {
          //this clicked panel
          var $this = $(this), 
              $target = $this.next(); 
    
          //slide up any open panels and remove active class
          $this.parent().children('dd').not($target).slideUp(); //Slide Up everything but the target one
    
          //remove any active class
          jQuery('.accordion > dt').removeClass('accordion-active');
          //add active class
          $this.addClass('accordion-active');
          //slide down target panel
          $target.addClass('active').slideToggle();
    
        return false;
      });
    

    Demo

    And actually you can simplify this to:

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

    Demo