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

JavascriptJqueryTwitter Bootstrap

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

Here it's the answer for those who are looking for a solution in Bootstrap 3(like myself).

The HTML part:

<div class="btn-group">
  <button type="button" class="btn btn-danger">Action</button>
  <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#demo">
    <span class="glyphicon glyphicon-minus"></span>
  </button>
</div>
<div id="demo" class="collapse in">Some dummy text in here.</div>

The js part:

$('.collapse').on('shown.bs.collapse', function(){
$(this).parent().find(".glyphicon-plus").removeClass("glyphicon-plus").addClass("glyphicon-minus");
}).on('hidden.bs.collapse', function(){
$(this).parent().find(".glyphicon-minus").removeClass("glyphicon-minus").addClass("glyphicon-plus");
});

Example accordion:

Bootply accordion example

Solution 2 - Javascript

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>

Solution 3 - Javascript

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");
    });
});

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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");
      });

Solution 7 - Javascript

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.

Solution 8 - Javascript

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.

Solution 9 - Javascript

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>

Solution 10 - Javascript

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');
});

Solution 11 - Javascript

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>

Solution 12 - Javascript

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>
      ...

Solution 13 - Javascript

@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.

Solution 14 - Javascript

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

Solution 15 - Javascript

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.

Solution 16 - Javascript

Here's a 2021 update for this very old question...

Bootstrap 5

Icon agnostic solution (doesn't use a specific icon lib) using CSS up/down triangles...

/* for up.down arrows after collapse items with submenus */
[data-bs-toggle="collapse"]::after {
  display: inline-block;
  margin-left: 0.255em;
  vertical-align: 0.255em;
  content: "";
  border-top: 0;
  border-right: 0.3em solid transparent;
  border-bottom: 0.3em solid;
  border-left: 0.3em solid transparent;
}

[data-bs-toggle="collapse"].collapsed::after {
  display: inline-block;
  margin-left: 0.255em;
  vertical-align: 0.255em;
  content: "";
  border-bottom: 0;
  border-right: 0.3em solid transparent;
  border-top: 0.3em solid;
  border-left: 0.3em solid transparent;
}

Demo using sidebar with collapse submenu

Solution 17 - Javascript

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>

Solution 18 - Javascript

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>

Solution 19 - Javascript

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.

Solution 20 - Javascript

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDarrenView Question on Stackoverflow
Solution 1 - JavascriptAndrei VeveView Answer on Stackoverflow
Solution 2 - JavascriptMartin WickmanView Answer on Stackoverflow
Solution 3 - JavascriptPhilipp HofmannView Answer on Stackoverflow
Solution 4 - JavascriptbafromcaView Answer on Stackoverflow
Solution 5 - JavascriptJohn MagnoliaView Answer on Stackoverflow
Solution 6 - Javascriptuser2273425View Answer on Stackoverflow
Solution 7 - JavascriptnoppeView Answer on Stackoverflow
Solution 8 - JavascriptAndreas BergströmView Answer on Stackoverflow
Solution 9 - JavascriptMikko OhtamaaView Answer on Stackoverflow
Solution 10 - JavascriptGeertView Answer on Stackoverflow
Solution 11 - JavascriptGeneral ElectricView Answer on Stackoverflow
Solution 12 - JavascriptJoshua BensonView Answer on Stackoverflow
Solution 13 - JavascriptRioBrewsterView Answer on Stackoverflow
Solution 14 - JavascriptPopov AndreyView Answer on Stackoverflow
Solution 15 - JavascriptMicah MontoyaView Answer on Stackoverflow
Solution 16 - JavascriptZimView Answer on Stackoverflow
Solution 17 - JavascriptSebastian SangervasiView Answer on Stackoverflow
Solution 18 - JavascriptJessycaFrederickView Answer on Stackoverflow
Solution 19 - JavascriptJunaidView Answer on Stackoverflow
Solution 20 - JavascriptWilliam WorleyView Answer on Stackoverflow