htmltwitter-bootstrap-3panelglyphicons

Bootstrap panel collapse incorrect icons with collabsible panel in another collapsible panel


I'm trying to use collapsible panels to show and hide data and am using glyph icons also to show the state. Initially on start up the glyph icons were not showing correctly (wrong states) but I found a fix for this using JS.

$('.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");
});

See this JSFiddle working correctly (i.e. icons show the correct state on start up and when minimizing and maximizing the individual collpasible panels)

However, I then put these 2 collapsible panels into a simple collabsible button (readmoreless) so these are only shown when the Read more button is presssed and hidden when Read less is pressed. I added some JS for this to toggle the text on the button (from Read more to Read less) when the button is pressed.

$(document).ready(function(){
 $("#readmoreless").on("hide.bs.collapse", function(){
   $(".btn2").html('Read more');
 });
 $("#readmoreless").on("show.bs.collapse", function(){
   $(".btn2").html('Read less');
 });
});

However the addition of this collapsible button area now breaks the panel icon states. They both seem to be affected by clicking on the Read more/Read less button and also both are affected when collapsing/opening one of the panels. The states of both panel area icons are always the same as each other even though one might be open and one closed.

See updated broken JSFiddle here.

Has anyone got any ideas how I can make this work?

Thanks!


Solution

  • I've replaced the .collapse with .panel-collapse to fix the icon states and changed the way you replace your text (read more / read less) by overriding the text() function return inside the click() function of your button.

    Here is what you should insert to your JS

    //Change icon states
    $('.panel-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");
    });
    
    //Read more or less
    $(document).ready(function () {
        $(".btn2").click(function () {
            $(this).text(function (i, text) {
                return text === "Read more" ? "Read less" : "Read more";
            })
        });
    });
    

    JSFiddle

    text() - function