itsclarke
itsclarke

Reputation: 8992

Plus - Minus Issue with jQuery Accordion

When I open and close the same menu, the plus/minus updates, but when I open one accordion, then another, both have minus signs.

http://codepen.io/anon/pen/uaytq

$('.collapse-toggle').click(function (e) {
    var that = $(this).parent();
    var accordion = that.find('.collapse-content');
    var icon = that.find('.icon');

    if (accordion.hasClass('open')) {
        accordion.animate({ height: 0 }, 300).removeClass('open');
        icon.html('+');
    } else {
        icon.html('+');
        $('.collapse-content.open').animate({ height: 0 }, 300).removeClass('open');
        var currentHeight = accordion.height(); //save current height
        accordion.css('height', 'auto');        //temporary switch height to auto
        var autoHeight = accordion.height();    //get auto height
        accordion.css('height', currentHeight); //switch back to current height
        accordion.animate({ height: autoHeight }, 300).addClass('open');
        icon.html('−');
    }
});

Upvotes: 0

Views: 653

Answers (2)

Jörn
Jörn

Reputation: 845

You could also change the icon with css by adding the .open class to the .collapse-group and using the following styles:

.collapse-group.open .icon:after {
    content: "+";
}

This way you have the ability to create other css selectors for the opened header and content section.

you could also check out this simple "pure jQuery" accordion: http://thecodeplayer.com/walkthrough/vertical-accordion-menu-using-jquery-css3

Upvotes: 0

Sadiq
Sadiq

Reputation: 2289

Change your else clause so that ALL the icons are changed to plus if you click a collapsed accordion.

Use $('.icon').html('+'); instead of icon.html('+'); at the beginning of your else clause.

$('.collapse-toggle').click(function (e) {
    var that = $(this).parent();
    var accordion = that.find('.collapse-content');
    var icon = that.find('.icon');

    if (accordion.hasClass('open')) {
        accordion.animate({ height: 0 }, 300).removeClass('open');
        icon.html('+');
    } else {
        $('.icon').html('+');  // This used to be icon.html('+');
        $('.collapse-content.open').animate({ height: 0 }, 300).removeClass('open');
        var currentHeight = accordion.height(); //save current height
        accordion.css('height', 'auto');        //temporary switch height to auto
        var autoHeight = accordion.height();    //get auto height
        accordion.css('height', currentHeight); //switch back to current height
        accordion.animate({ height: autoHeight }, 300).addClass('open');
        icon.html('−');
    }
});

Demo

Upvotes: 1

Related Questions