Vasilios Betoglou
Vasilios Betoglou

Reputation: 65

Bootstrap - Maintaining <div> collapse state between refresh

A bit of a js/jquery novice - I'm using Bootstrap and data-toggle + collapse classes to show/hide divs. I've been scouring the 'net trying to find something that will maintain the state of all divs, whether identified by a unique ID or a CLASS, between page refreshes. I've seen discussions on cookies and local storage, I don't think I care which method is used (although I've had errors with $.cookie is not a function, so maybe local storage is better?).

The issue is most examples deal with maintaining accordion states, which I don't think exactly apply here. I've tried modifying various code examples but they just don't quite seem to work.

Here is an example of my code:

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<div class="panel panel-danger">
  <div data-toggle="collapse" href="#duesoon" style="cursor: pointer;" class="panel-heading">
    <font class="panel-title"><span class='glyphicon glyphicon-fire'></span> Top 5 Expiring Tasks</font>
  </div>
  <div id="duesoon" class="collapse">
    <table class="table table-hover table-striped table-condensed">
      <thead>
        <tr>
          <th class='col-md-7'>Name</th>
          <th class='col-md-5'>End Date</th>
        </tr>
      </thead>
      <tbody>
        <tr style="cursor: pointer;" onclick="document.location = '?action=view&type=project&id=2">
          <td><span class='glyphicon glyphicon-triangle-right'></span> Take Out The Trash</td>
          <td>Yesterday</td>
        </tr>
      </tbody>
    </table>
  </div>
  <div data-toggle="collapse" href="#urgency" style="cursor: pointer;" class="panel-heading">
    <font class="panel-title"><span class='glyphicon glyphicon-fire'></span> Top 5 Urgent Tasks</font>
  </div>
  <div id="urgency" class="collapse">
    <table class="table table-hover table-striped table-condensed">
      <thead>
        <tr>
          <th class='col-md-7'>Name</th>
          <th class='col-md-5'>Priority</th>
        </tr>
      </thead>
      <tbody>
        <tr style="cursor: pointer;" onclick="document.location = '?action=view&type=project&id=1">
          <td><span class='glyphicon glyphicon-triangle-right'></span> Save the Whales</td>
          <td>Critical</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

As you can see, there's a link or a button or something that toggles showing/hiding a div.

Same thing on JSFiddle: http://jsfiddle.net/w8psgvaa/2/

I found this code example;

 $('.collapse').on('hidden', function() {
       // store this.id
 }).on('shown', function() {
       // delete this.id
 });

 $(document).ready(function(){
     $(".collapse").collapse().each(function(){
         if( isStored( this.id ) ) {
             $( this ).collapse( 'hide' );
         }
     });
 });​

But unfortunately it's incomplete. and some divs start out collapsed (as in my example). Any help is appreciated!

Upvotes: 2

Views: 8451

Answers (2)

Roubi
Roubi

Reputation: 2106

Here is a working example, using Bootstrap panel-collapse and LocalStorage, similar to Hidde's answer. I'm using JSON "stringify" and "parse" functions to store my ids in localStorage, which stores everything as strings. I also use Bootstrap's collapse events.

// On document ready

var shownOnRefresh = [];
localStorage.setItem('shownOnRefresh', JSON.stringify(shownOnRefresh));

$('#myParentElement').on('shown.bs.collapse', '.panel-collapse', function() {
        shownOnRefresh = JSON.parse(localStorage.getItem('shownOnRefresh'));
        if ($.inArray($(this).attr('id'), shownOnRefresh) == -1) {
            shownOnRefresh.push($(this).attr('id'));
        };
        localStorage.setItem('shownOnRefresh', JSON.stringify(shownOnRefresh));
});

$('#myParentElement').on('hidden.bs.collapse', '.panel-collapse', function() {
        shownOnRefresh = JSON.parse(localStorage.getItem('shownOnRefresh'));
        shownOnRefresh.splice( $.inArray($(this).attr('id'), shownOnRefresh), 1 );//remove item from array
        localStorage.setItem('shownOnRefresh', JSON.stringify(shownOnRefresh));
});

// On page refresh
var shownOnRefresh = JSON.parse(localStorage.getItem('shownOnRefresh'));
for (var i in shownOnRefresh ) {
    $('#' + shownOnRefresh [i]).addClass('in');
}

I'm a jquery novice, so this code can certainly be optimized, but it does the job.

Upvotes: 1

Hidde
Hidde

Reputation: 11961

You are looking in the right direction. My solution would be the following.

Use LocalStorage, available in modern browsers.

  • When a div is collapsed: remove the div's ID from the storage
  • When a div is opened: add the div's ID from the storage.

This is as easy as

var shown = []

// On collapse
shown.remove($(this).attr('id'));
localStorage.setItem('shown', shown);

// On open
shown.push($(this).attr('id'));
localStorage.setItem('shown', shown);

// On page load
var shown = localStorage.getItem('shown');
for (var s in shown) {
    $('#' + s).show(); // Or whatever API you use to un-collapse the div
}

More information: http://diveintohtml5.info/storage.html

Upvotes: 4

Related Questions