Hazard Hazard - 2 months ago 11
HTML Question

Toggle the glyphicon with bootstrap collapse

I have

glyphicon-chevron-down
when div is in
collapsed
state,i want to replace it with
glyphicon-chevron-up
when the div is in
collapse in
state.I have many of these
collapsible
divs in my project.So i need to
toggle
the
glyphicon
on press of particular collapsibe content(or div).

HTML

<div class="divcontainer">
<span>Click -----></span>
<span class="glyphicon glyphicon-chevron-down" data-toggle="collapse" href="#collapsecontent"></span>
</div>
<div class="collapse" id="collapsecontent">
content
</div>


JavaScript

$(document).ready(function () {
$('.glyphicon-chevron-down').click(function () {
$(this).parent("div").find(".glyphicon-chevron-down")
.toggleClass("glyphicon-chevron-up");
});
});


Fiddle here

Answer

Your JS is putting an emphasis on the wrong thing. Find is very slow and best avoided if possible -- and it's very possible here. Just change it to this:

$(document).ready(function () {
    $('.glyphicon').click(function () {
        $(this).toggleClass("glyphicon-chevron-down").toggleClass("glyphicon-chevron-up");
    });
});

JS Fiddle: http://jsfiddle.net/ft4mnynh/