Saving Bootstrap collapse state between page refresh/page swap

Viewed 1161

I have this BS navbar that you can collapse, and I want it to save the state when I change page or refresh the current page.

home.php

<!-- Side Navbar -->
<nav class="side-navbar">
  <div class="side-navbar-wrapper">
    <div class="sidenav-header d-flex align-items-center justify-content-center">
      <div class="sidenav-header-inner text-center"><img src="img/marcus_avatar.png" alt="person" class="img-fluid rounded-circle">
        <h2 class="h5 text-uppercase"><?php echo $_COOKIE['userName']; ?></h2><span class="text-uppercase">Web Admin</span>
      </div>
      <div class="sidenav-header-logo"><a href="home" class="brand-small text-center"> <strong>S</strong><strong class="text-primary">F</strong></a></div>
    </div>
    <div class="main-menu">
      <ul id="side-main-menu" class="side-menu list-unstyled">                  
        <li class="active"><a href="home"> <i class="fa fa-home"></i><span>Home</span></a></li>
        <li> <a href="users"><i class="fa fa-users"></i><span>Users</span></a></li>
        <li> <a href="upload"><i class="fa fa-upload"></i><span>Upload</span></a></li>
        <li><a href="files"><i class="fa fa-file"></i><span>My Files</span></a></li>
      </ul>
    </div>
  </div>
</nav>

jsfile.js

$(".side-navbar").on('shown.bs.collapse', function ()
{
    var active = $(this).attr('id');
    $.cookie(active, "1");
});

$(".side-navbar").on('hidden.bs.collapse', function ()
{
    var active = $(this).attr('id');
    $.removeCookie(active);
});

$(document).ready(function(){
    var panels=$.cookie(); //get all cookies
    for (var panel in panels){ //<-- panel is the name of the cookie
        if ($("#"+panel).hasClass('shrink')) // check if this is a panel
        {
            $("#"+panel).collapse("show");
        }
    }    
});

I want it to work like this: http://jsfiddle.net/03u0bfst/3/ but I just can't get it to work for the life of me!

0 Answers
Related