最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Bootstrap - Maintaining <div> collapse state between refresh - Stack Overflow

programmeradmin6浏览0评论

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=".1.4.min.js"></script>
<script src=".3.4/js/bootstrap.min.js"></script>
<link href=".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>

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./jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn./bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn./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/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 inplete. and some divs start out collapsed (as in my example). Any help is appreciated!

Share Improve this question asked May 23, 2015 at 18:33 Vasilios BetoglouVasilios Betoglou 652 silver badges7 bronze badges 3
  • you get the cookie error because you are not including the js library for it --- github./carhartl/jquery-cookie or github./js-cookie/js-cookie – Tasos Commented May 23, 2015 at 18:37
  • Hi Tasos, yes it is not included in the sample above, but I have included it when trying some of the cookie code examples and I was still getting that error. Perhaps it's a conflict with something else or an issue with the code I was using. Thanks! – Vasilios Betoglou Commented May 23, 2015 at 18:46
  • Thanks humble, I'll look more into this and see if I can apply it to what I'm trying to acplish. I'm more of a back-end guy (PHP) - but I need to learn more about front-end coding. – Vasilios Betoglou Commented May 23, 2015 at 18:47
Add a ment  | 

2 Answers 2

Reset to default 4

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

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.

发布评论

评论列表(0)

  1. 暂无评论