DaandV
DaandV

Reputation: 1

Save multiple bootstrap panels state using localstorage

I saw this topic with a part of the answer were I was looking for: Saving multiple panel's collapsed state using cookies with $.cookie()

But, when I use the code from the answer, the panels are already closed. I'd like to have the panels open by default. Instead of closed.

This is the code I used:

$(".panel .panel-collapse").on('shown.bs.collapse', function ()
{
    var active = $(this).attr('id');
    var panels= localStorage.panels === undefined ? new Array() : JSON.parse(localStorage.panels);
    if ($.inArray(active,panels)==-1) //check that the element is not in the array
        panels.push(active);
    localStorage.panels=JSON.stringify(panels);
});

$(".panel .panel-collapse").on('hidden.bs.collapse', function ()
{
    var active = $(this).attr('id');
    var panels= localStorage.panels === undefined ? new Array() : JSON.parse(localStorage.panels);
    var elementIndex=$.inArray(active,panels);
    if (elementIndex!==-1) //check the array
    {        
        panels.splice(elementIndex,1); //remove item from array
    }
    localStorage.panels=JSON.stringify(panels); //save array on localStorage
});

var panels=localStorage.panels === undefined ? new Array() : JSON.parse(localStorage.panels); //get all panels
    for (var i in panels){ //<-- panel is the name of the cookie
        if ($("#"+panels[i]).hasClass('panel-collapse')) // check if this is a panel
        {
            $("#"+panels[i]).collapse("show");
        }
    }

This is the working fiddle.

Hopefully I'll get a good answer.

Thanks!

Upvotes: 0

Views: 572

Answers (1)

Jyoti Pathania
Jyoti Pathania

Reputation: 4989

Uppdated:

Try this:

 function restoreActiveAccordionGroup() {
             var last = [];
             last = $.cookie();
            if (last) {

                //remove default collapse settings from all panels
                $("#accordion").removeClass('in');
                for (var i in last) {
                //restore the last visible panel group in all nested levels
                $("#" + i).addClass("in");
                }

            }
        }

Old

Just add in class to every panel-collapse class. It will make all panel remain open by default once the page load.

<div id="panel1" class="panel-collapse collapse in">
        <div class="panel-body">
        </div>
 </div>

Upvotes: 1

Related Questions