Search code examples
jquerycsstwitter-bootstraptwitter-bootstrap-2

Display an icon when open and another when closed (jQuery Bootstrap)


I need the following, when the page is loaded must show one open accordion with minus icon, and when closed the plus icon should change.

Here's an example in fiddle

$('div.accordion-body').on('shown', function () {
    $(this).parent("div").find(".icon-plus")
                         .removeClass("icon-plus")
                         .addClass("icon-minus");
});

$('div.accordion-body').on('hidden', function () {
    $(this).parent("div").find(".icon-minus")
                         .removeClass("icon-minus")
                         .addClass("icon-plus");
});

How to make to display open accordion with default icon minus?


Solution

  • You can see a working example where I adapted to your Fiddle to make it work.

    function toggleChevron(e) {
        jQuery(e.target)
        .prev('.accordion-heading')
        .find("i")
        .toggleClass('icon-plus icon-minus');
    }
    jQuery('#comuniArchivos').on('hidden.bs.collapse', toggleChevron);
    jQuery('#comuniArchivos').on('shown.bs.collapse', toggleChevron);
    
    jQuery('.panel-default').on('show.bs.collapse', function() {
        jQuery(this).addClass('active');
    });
    
    jQuery('.panel-default').on('hide.bs.collapse', function() {
        jQuery(this).removeClass('active');
    });
    

    That first toggle in your HTML needs to be icon-minus because it's expanded by default.