[javascript] Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

I've set up this simple version of the Bootstrap accordion:

Simple accordion: http://jsfiddle.net/darrenc/cngPS/

Currently the icon only points down, but does anyone know what JS would be needed to be implemented so as to change the class of the icon to:

<i class="icon-chevron-up"></i>

...so that it points up when expanded and toggles back to down again when collapsed, and so fourth?

This question is related to javascript jquery twitter-bootstrap

The answer is


Added to @muffls answer so that this works with all twitter bootstrap collapse and makes the change to the arrow before the animatation starts.

$('.collapse').on('show', function(){
    $(this).parent().find(".icon-chevron-left").removeClass("icon-chevron-left").addClass("icon-chevron-down");
}).on('hide', function(){
    $(this).parent().find(".icon-chevron-down").removeClass("icon-chevron-down").addClass("icon-chevron-left");
});

Depending on your HTML structure you may need to modify the parent().


This is how I do it without any js.

I used the icon glyphicon-triangle-right but it works with any other icon, what it does is that it applies a 90 degrees rotation to the icon when the panel is open or not. I'm using Bootstrap 3.3.5 for this one.

CSS Code

h4.panel-title a {
    display: block;

}
h4.panel-title a.collapsed .glyphicon-triangle-right {
        color: #ada9a9 !important;
        transform: rotate(0deg);
}
h4.panel-title a .glyphicon-triangle-right {
        color: #515e64 !important;
        transform: rotate(90deg);
}

This is the HTML structure taken from the Bootstrap example

<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
                            <div class="panel panel-default">
                                <div class="panel-heading" role="tab" id="headingOne">
                                    <h4 class="panel-title">
                                        <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                                            Proven Expertise
                                            <span class="glyphicon glyphicon-triangle-right pull-right" aria-hidden="true"></span>
                                        </a>
                                    </h4>
                                </div>
                                <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
                                    <div class="panel-body">
                                        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
                                    </div>
                                </div>
                            </div>

                        </div>

The Bootstrap Collapse has some Events that you can react to:

$(document).ready(function(){    
    $('#accordProfile').on('shown', function () {
       $(".icon-chevron-down").removeClass("icon-chevron-down").addClass("icon-chevron-up");
    });

    $('#accordProfile').on('hidden', function () {
       $(".icon-chevron-up").removeClass("icon-chevron-up").addClass("icon-chevron-down");
    });
});

The most readable CSS-only solution would probably be to use the aria-expanded attribute. Remember that you'll need to add aria-expanded="false" to all collapse-elements as this is not set on load (only on first click).

The HTML:

<h2 data-toggle="collapse" href="#collapseId" aria-expanded="false">
    <span class="glyphicon glyphicon-chevron-right"></span>
    <span class="glyphicon glyphicon-chevron-down"></span> Title
</h2>

The CSS:

h2[aria-expanded="false"] span.glyphicon-chevron-down,
h2[aria-expanded="true"] span.glyphicon-chevron-right
{
    display: none;
}

h2[aria-expanded="true"] span.glyphicon-chevron-down,
h2[aria-expanded="false"] span.glyphicon-chevron-right
{
    display: inline;
}

Works with Bootstrap 3.x.


I think the best codes are these:

  $('#accordion1').collapse({
    toggle: false
  }).on('show',function (e) {
        $(e.target).parent().find(".icon-chevron-down").removeClass("icon-chevron-down").addClass("icon-chevron-up");
      }).on('hide', function (e) {
        $(e.target).parent().find(".icon-chevron-up").removeClass("icon-chevron-up").addClass("icon-chevron-down");
      });

Here is my solution which is further refined from one posted by @john-magnolia and solves some of its issues

/**
 * Toggle on/off arrow for Twitter Bootstrap collapsibles.
 *
 * Multi-collapsible-friendly; supports several collapsibles in the same group, on the same page.
 */
function animateCollapsibles() {

    $('.collapse').on('show', function() {
        var $t = $(this);
        var header = $("a[href='#" + $t.attr("id") + "']");
        header.find(".icon-chevron-right").removeClass("icon-chevron-right").addClass("icon-chevron-down");
    }).on('hide', function(){
        var $t = $(this);
        var header = $("a[href='#" + $t.attr("id") + "']");
        header.find(".icon-chevron-down").removeClass("icon-chevron-down").addClass("icon-chevron-right");
    });
}

And here is the example markup:

<div class="accordion" id="accordion-send">
    <div class="accordion-group">
        <div class="accordion-heading">
            <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion-send" href="#collapse-refund">
                <i class="icon icon-chevron-right"></i> Send notice
            </a>
        </div>
        <div id="collapse-refund" class="accordion-body collapse">
            <div class="accordion-inner">
                <p>Lorem ipsum Toholampi city</p>
            </div>
        </div>
    </div>
</div>

A bootstrap v3 solution (where the events have different names), also using only one jQuery selector (as seen here):

$('.accordion').on('hide.bs.collapse show.bs.collapse', function (n) {
    $(n.target).siblings('.panel-heading').find('i.glyphicon').toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
});

@RobSadler:

RE Martin Wickman's CSS only version...

You can get around that problem by putting accordion-caret on the anchor tag and giving it a collapsed class by default. Like so:

<div class="accordion-group">
<div class="accordion-heading">
    <a class="accordion-toggle accordion-caret collapsed" data-toggle="collapse" href="#collapseOne">
        <strong>Header</strong>
    </a>
</div>
<div id="collapseOne" class="accordion-body collapse in">
    <div class="accordion-inner">
        Content
    </div>
</div>

That worked for me.


For a CSS-only (and icon-free) solution using Bootstrap 3 I had to do a bit of fiddling based on Martin Wickman's answer above.

I didn't use the accordion-* notation because it's done with panels in BS3.

Also, I had to include in the initial HTML aria-expanded="true" on the item that's open at page load.

Here is the CSS I used.

.accordion-toggle:hover { text-decoration: none; }
.accordion-toggle:hover span, .accordion-toggle:hover strong { text-decoration: underline; }
.accordion-toggle:before { font-size: 25px; }
.accordion-toggle[data-toggle="collapse"]:before { content: "+"; margin-right: 0px; }
.accordion-toggle[aria-expanded="true"]:before { content: "-"; margin-right: 0px; }

Here is my sanitized HTML:

<div id="acc1">    
    <div class="panel panel-default">
        <div class="panel-heading">
            <span class="panel-title">
                <a class="accordion-toggle" data-toggle="collapse" aria-expanded="true" data-parent="#acc1" href="#acc1-1">Title 1
                    </a>
            </span>
        </div>
        <div id=“acc1-1” class="panel-collapse collapse in">
            <div class="panel-body">
                Text 1
            </div>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading">
            <span class="panel-title">
                <a class="accordion-toggle" data-toggle="collapse" data-parent="#acc1” href=“#acc1-2”>Title 2
                    </a>
            </span>
        </div>
        <div id=“acc1-2” class="panel-collapse collapse">
            <div class="panel-body">
                Text 2                  
            </div>
        </div>
    </div>
</div>

Shortest possible answer.

HTML

<a data-toggle="collapse" data-parent="#panel-quote-group" href="#collapseQuote">
    <span class="toggle-icon glyphicon glyphicon-collapse-up"></span>
</a>

JS:

<script type="text/javascript">
 $(function () {
     $('a[data-toggle="collapse"]').click(function () {
     $(this).find('span.toggle-icon').toggleClass('glyphicon-collapse-up glyphicon-collapse-down');
     })
 })
 </script>

And of course, you can use anything for a selector instead of anchor tag a and you can also use specific selector instead of this if your icon lies outside your clicked element.


Use CSSes pseudo-selector :after using Bootstrap 3's integrated Glyphicons for a no JS answer with minor modification to your HTML...

CSS

.panel-heading [data-toggle="collapse"]:after
{
    font-family: 'Glyphicons Halflings';
    content: "\e072"; /* "play" icon */
    float: right;
    color: #b0c5d8;
    font-size: 18px;
    line-height: 22px;

    /* rotate "play" icon from > (right arrow) to down arrow */
    -webkit-transform: rotate(-90deg);
    -moz-transform:    rotate(-90deg);
    -ms-transform:     rotate(-90deg);
    -o-transform:      rotate(-90deg);
    transform:         rotate(-90deg);
}
.panel-heading [data-toggle="collapse"].collapsed:after
{
    /* rotate "play" icon from > (right arrow) to ^ (up arrow) */
    -webkit-transform: rotate(90deg);
    -moz-transform:    rotate(90deg);
    -ms-transform:     rotate(90deg);
    -o-transform:      rotate(90deg);
    transform:         rotate(90deg);
}

HTML

Add class="collapsed" to any anchor tags that are closed by default.

This will turn anchors such as

<a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">

into

<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">

CodePen Live Example

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

Screenshot

How it appears in JSBin


If anyone is interested this is how you do it with BS3 since they changed the event names:

$('.collapse').on('show.bs.collapse', function(){
  var i = $(this).parent().find('i')
  i.toggleClass('fa-caret-right fa-caret-down');
}).on('hide.bs.collapse', function(){
  var i = $(this).parent().find('i')
  i.toggleClass('fa-caret-down fa-caret-right');
});

You simply change the class names in the example to the ones you use in your case.


Here is a solution that creates a section that is expandable using somewhat material design, bootstrap 4.5/5 alpha and entirely non-javascript.

Style for head section

<style>
[data-toggle="collapse"] .fa:before {
    content: "\f077";
}

[data-toggle="collapse"].collapsed .fa:before {
    content: "\f078";
}
</style>

Body html

<div class="pt-3 pb-3" style="border-top: 1px solid #eeeeee; border-bottom: 1px solid #eeeeee; cursor: pointer;">
<a href="#expandId" class="text-dark float-right collapsed" data-toggle="collapse" role="button" aria-expanded="false" aria-controls="expandId">
    <i class="fa" aria-hidden="false"></i>
</a>
<a href="#expandId" class="text-dark collapsed" data-toggle="collapse" role="button" aria-expanded="false" aria-controls="expandId">Expand Header</a>
<div class="collapse" id="expandId">
    CONTENT GOES IN HERE
</div>

Here is my approach for Bootstrap 2.x. It is just some css. No JavaScript needed:

    .accordion-caret .accordion-toggle:hover {
        text-decoration: none;
    }
    .accordion-caret .accordion-toggle:hover span,
    .accordion-caret .accordion-toggle:hover strong {
        text-decoration: underline;
    }
    .accordion-caret .accordion-toggle:before {
        font-size: 25px;
        vertical-align: -3px;
    }
    .accordion-caret .accordion-toggle:not(.collapsed):before {
        content: "?";
        margin-right: 0px;
    }
    .accordion-caret .accordion-toggle.collapsed:before {
        content: "?";
        margin-right: 0px;
    }

Just add class accordion-caret to the accordion-group div, like this:

<div class="accordion-group accordion-caret">
    <div class="accordion-heading">
        <a class="accordion-toggle" data-toggle="collapse" href="#collapseOne">
            <strong>Header</strong>
        </a>
    </div>
    <div id="collapseOne" class="accordion-body collapse in">
        <div class="accordion-inner">
            Content
        </div>
    </div>
</div>

Another no-javascript solution that uses the collapse functionality itself:

/* Prevent block display and transition animation */
.expand-icon.collapse.in,
.collapse-icon.collapse.in {
  display: inline; }
.expand-icon.collapsing {
  display: none; }

/* HTML Toggler with glyphicons */
<a data-toggle="collapse" href=".my-collapse">
 <span class="my-collapse collapse-icon collapse in">
  <span class="glyphicon glyphicon-collapse-up"></span>
 </span>
 <span class="my-collapse expand-icon collapse">
  <span class="glyphicon glyphicon-expand"></span>   
 </span>
</a>

None of the above worked for me but I came up with this and it worked:

function toggleChevron(el) {
  if ($(el).find('i').hasClass('icon-chevron-left'))
      $(el).find('.icon-chevron-left').removeClass("icon-chevron-left").addClass("icon-chevron-down");
  else 
      $(el).find('.icon-chevron-down').removeClass("icon-chevron-down").addClass("icon-chevron-left");
}

HTML implementation:

<div class="accordion" id="accordion-send">
  <div class="accordion-group">
    <div class="accordion-heading" onClick="toggleChevron(this)">
      <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion-send" href="#collapse-refund">
        <i class="icon icon-chevron-right"></i> Send notice
      </a>
      ...

This has been answered by numerous ways but what I came up with was the simplest and easiest for me with Bootstrap 3 and font awesome. I just did

$('a.toggler').on('click', function () {$('i', this).toggleClass('fa-caret-up');});

This just toggles the CSS class of the icon I want to show. I add the class toggler to the item I want to apply this to. This can be added onto any item you want to toggle an icon.


For Bootstrup 3.2 + FontAwesome

$(document).ready(function(){    
    $('#accordProfile').on('shown.bs.collapse', function () {
       $(".fa-chevron-down").removeClass("fa-chevron-down").addClass("fa-chevron-up");
    });

    $('#accordProfile').on('hidden.bs.collapse', function () {
       $(".fa-chevron-up").removeClass("fa-chevron-up").addClass("fa-chevron-down");
    });
});

Sometimes you have to write so. If so

$('.collapsed span').removeClass('fa-minus').addClass('fa-plus');

Automatically generated (class="collapsed"), when you press the hide menu.

ps when you need to create a tree menu


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation