RCNeil
RCNeil

Reputation: 8779

Toggle an Accordion with JQuery

I had an accordion given to me that is not toggling each tab open and close. It only closes the tab when another title is selected, but I'd like the ability for the user to close it on click as well. I'm not sure how to edit this Jquery to allow this to happen.

jQuery("ul.gdl-accordion li").each(function(){
    jQuery(this).children(".accordion-content").css('height', function(){ 
        return jQuery(this).height(); 
    });
    if(jQuery(this).index() > 0){
        jQuery(this).children(".accordion-content").css('display','none');
    }else{
        jQuery(this).find(".accordion-head-image").addClass('active');
    }       

    jQuery(this).children(".accordion-head").bind("click", function(){
        jQuery(this).children().addClass(function(){
            if(jQuery(this).hasClass("active")) return "";
            return "active";
        });
        jQuery(this).siblings(".accordion-content").slideDown();
        jQuery(this).parent().siblings("li").children(".accordion-content").slideUp();          jQuery(this).parent().siblings("li").find(".active").removeClass("active");
    });
});

I'm assuming it's somewhere in the .click function, in that if statement... but I'm not sure why.

I'm also not sure why it is defaulting the first tab as open... is there a way to modify that as well?

http://jsfiddle.net/FKAAM/

Any advice is greatly appreciated. Many thanks SO.

Upvotes: 2

Views: 29625

Answers (4)

Paweł Witek
Paweł Witek

Reputation: 181

here's the acordion link and full jQuery code:

jQuery(document).ready(function($){
  //you can now use $ as your jQuery object.
  $(".panel-heading").click(function() {
    $(this).parent().toggleClass('active').find('.panel-body').slideToggle('fast');
    $(".panel-heading").not(this).parent().removeClass('active').find('.panel-body').slideUp('fast');
  });
});

Upvotes: 2

Lowkase
Lowkase

Reputation: 5699

Use slideToggle() instead:

jQuery(this).siblings(".accordion-content").slideDown();

jQuery(this).siblings(".accordion-content").slideToggle();

http://jsfiddle.net/FKAAM/4/

Upvotes: 4

Wolf
Wolf

Reputation: 2150

I will suggest you to use jQuery accordion

$(function() {
        $( "#accordion" ).accordion({
            collapsible: true
        });
    });

Check the example here. I guess this is what you needed.

Upvotes: -2

Francis Lewis
Francis Lewis

Reputation: 8990

Add:

collapsible: true

to your accordion options, then users will be able to click to close it.

(jQuery UI Accordion: http://jqueryui.com/accordion/)

Upvotes: 1

Related Questions