How to use CSS to modify an icon with the bootstrap collapse

Issue

I’m trying to build a list with subpoints that collapse on command using the bootstrap collapse. This has worked fine, but I need to add an arrow that points right when the collapse is up, and down when it’s dropped down.

This is my HTML…

<ul>
<li data-toggle="collapse" data-target="#Sub1">List Item One <em class="glyphicon glyphicon-chevron-right"></em><em class="glyphicon glyphicon-chevron-down"></em>
<ul class="collapse" id="Sub1">
<li>Sub-item</li>
</ul>
<li>List Item Two</li>
</ul>

Currently I’m using this CSS to modify it…

.collapse {display: none;}
.collapse.in {display: block;}
.collapsed > .glyphicon .glyphicon-chevron-down {display: inline-block;}
.collapsed > .glyphicon .glyphicon-chevron-right {display: none;}

http://jsfiddle.net/ddx0c3c2/

The problem I’m encountering is that both icons are displaying, and not disappearing when the class changes. Is it possible to do this with just CSS, or do I need to use jQuery?

Solution

Here you are: JSFiddle. I’ve solved it with jQuery.

Your first “mistake” was to have a false CSS-Selector order. Your glyphicon isn’t inside the .collapse class.

HTML:

<ul>
    <li data-toggle="collapse" data-target="#Sub1">List Item One <em class="glyphicon glyphicon-chevron-right arrow_show"></em><em class="glyphicon glyphicon-chevron-down"></em>

        <ul class="collapse" id="Sub1">
            <li>Sub-item</li>
        </ul>
        <li>List Item Two</li>
</ul>

CSS:

.collapse {
  display: none;
}

.collapse.in {
  display: block;
}

.glyphicon {
    display:none;
}
.arrow_show {
    display: inline;
}

JS:

$('li[data-target="#Sub1"]').on("click", function() {
  $('.glyphicon-chevron-right').toggleClass('arrow_show');
  $('.glyphicon-chevron-down').toggleClass('arrow_show');
 })

Answered By – ohboy21

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published