gnudle
gnudle

Reputation: 323

Retain Twitter Bootstrap Collapse state on Page refresh/Navigation

I'm using Bootstrap "collapse" plugin to make an accordion for a long list of links. The accordion-body tag includes "collapse" so all the groups are collapsed when the page loads. When you open a group and click on a link, it takes you to a new page to see some detail and then you click a back link or the browser back to return to the list. Unfortunately, when you return the accordion is back in its collapsed state and you have to open the group again and find where you were. I anticipate a lot of this back and forth navigation and this behavior is going to be frustrating.

Is there some way to preserve the user's place and go back to it, or just prevent the page from reloading or the javascript from firing again.

I thought the solution might be along these lines, but not sure. Twitter bootstrap: adding a class to the open accordion title

Upvotes: 32

Views: 51740

Answers (10)

Roger Camargo
Roger Camargo

Reputation: 66

Regarding the @JonatanRek answer. I did a small adjustment regarding the 'collapse' class, which it worked better using the 'show' instead:


function store_state(el, state) {
  localStorage.setItem("coll_" + el.id, state);
}

function restore_initial_state() {
  document.querySelectorAll(".store-collapse").forEach(function (el) {
    let itemState = localStorage.getItem("coll_" + el.id)
    let show = (itemState === "true")
    if (itemState && show) {
      el.classList.add("show")
    }
  });
}

window.addEventListener('load', () => {
  restore_initial_state()
}, false)

document.querySelectorAll(".store-collapse").forEach(function (el) {
  el.addEventListener('hidden.bs.collapse', function () {
    store_state(el, false) // hide
  });
  el.addEventListener('shown.bs.collapse', function () {
    store_state(el, true) // show
  });
});

Upvotes: 0

JonatanRek
JonatanRek

Reputation: 1

If anyone still interested there there is my tested code for Bootstrap 5.3

 <script defer type="text/javascript">
    window.addEventListener('load',
        function() {
            document.querySelectorAll(".store-collapse").forEach(function(el) {
                el.addEventListener("shown.bs.collapse", function() {
                    localStorage.setItem("coll_" + el.id, true);
                    console.log('SHOW ' + el.id + "$");
                })
            });
            document.querySelectorAll(".store-collapse").forEach(function(el) {
                el.addEventListener("hidden.bs.collapse", function() {
                    localStorage.setItem("coll_" + el.id, false);
                    console.log('HIDE ' + el.id + "$");
                })
            });

            document.querySelectorAll(".store-collapse").forEach(function(el) {
                console.log('EACH ' + el.id);
                if (localStorage.getItem("coll_" + el.id) === "true") {
                    console.log('INIT SHOW ' + el.id);
                    el.classList.add("show")
                } else if (localStorage.getItem("coll_" + el.id) === "false") {
                    console.log('INIT HIDE ' + el.id);
                    el.classList.remove("show")
                }
            });
        }, false);
</script>

Upvotes: 0

Robert Lujo
Robert Lujo

Reputation: 16391

For those who don't have/don't want to use jQuery/$, this is Vanilla Javascript version that works for me (Bootstrap version 5):

<script defer type="text/javascript">
  window.addEventListener('load',
    function () {
      document.querySelectorAll(".store-collapse").forEach(function (el) {
          el.addEventListener("shown.bs.collapse", function () {
              localStorage.setItem("coll_" + el.id, true);
              console.log('SHOW ' + el.id + "$");
          })
      });
      document.querySelectorAll(".store-collapse").forEach(function (el) {
          el.addEventListener("hidden.bs.collapse", function () {
              localStorage.setItem("coll_" + el.id, false);
              console.log('HIDE '+ el.id + "$");
          })
      });
  
      document.querySelectorAll(".store-collapse").forEach(function (el) {
          console.log('EACH ' + el.id);
          if (localStorage.getItem("coll_" + el.id) === "true") {
              console.log('INIT SHOW '+ el.id);
              el.classList.remove("collapse")
          } else if (localStorage.getItem("coll_" + el.id) === "false") {
              console.log('INIT HIDE '+ el.id);
              el.classList.add("collapse")
          }
      });
  }, false);
</script>

Some explanations:

  • store-collapse class I have added in order to precisely select elements for which I want to enable save/restore collapse state to/from local storage. Example:
    <div class="store-collapse" id="status_table"> 
      <table class="table">
      ...
    </div>
    
    <div class="store-collapse" id="info_table"> 
      <table class="table">
      ...
    </div>
  • instead of calling some Bootstrap Javascript code/instatiate objects, I chose to work with Bootstrap classes - and it works with no issues.

References:

Upvotes: 1

Gass
Gass

Reputation: 9412

Updated Answer

Okay guys, so I invested some time trying to make it work. Mostly because all the answers I found where super old and not updated.

This will work with:

  • Bootstrap 3.x.x
  • Bootstrap 4.x.x
  • Bootstrap 5.x.x

Note: cookies where updated to a new Github repository https://github.com/js-cookie/js-cookie the usage has been changed e.g instead of $.cookie('name'); now is Cookies.get('name');

Include

<script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script>    

Script

$(document).ready(function() {

      var last=Cookies.get('activeAccordionGroup');

      if (last!=null) {
          //remove default collapse settings
          $("#accordion .collapse").removeClass('show');
          //show the last visible group
          $("#"+last).collapse("show");
      }
 });

 //when a group is shown, save it as the active accordion group
 $("#accordion").bind('shown.bs.collapse', function() {
      var active=$("#accordion .show").attr('id');
      Cookies.set('activeAccordionGroup', active);
  });

Changes:

  • Bootstrap event is no longer shown it's shown.bs.collapse
  • Cookies usage

Accordion HTML

<div id="accordion">
  <div class="card">
    <div class="card-header" id="headingOne">
      <h5 class="mb-0">
        <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </button>
      </h5>
    </div>

    <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingTwo">
      <h5 class="mb-0">
        <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          Collapsible Group Item #2
        </button>
      </h5>
    </div>
    <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingThree">
      <h5 class="mb-0">
        <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
          Collapsible Group Item #3
        </button>
      </h5>
    </div>
    <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordion">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>

Upvotes: 2

kheit
kheit

Reputation: 287

Another option available is to use the url hash.

$(document).ready(function () {
    var hash = window.location.hash;
    if (hash) {
        $("#accordion .panel-collapse").removeClass('in');
        $(hash).addClass('in');
    }

    $('#accordion').on('shown.bs.collapse', function () {
        var activeId = $("#accordion .in").attr('id');
        window.location.hash = activeId;
    });

    $('#accordion').on('hidden.bs.collapse', function () {
        window.location.hash = '';
    });
});

Upvotes: 2

gleichdanke
gleichdanke

Reputation: 171

Thanks for this, it works. I modified it a bit to simply retain the show/hide state of a specific DIV (and not specific to showing only one DIV in a list of DIVs).

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>

<script language="javascript" type="text/javascript">
    function retainDivCollapsedState(nameOfDiv, nameOfHeader) {
        // when the div is shown, save a cookie with a value of 'true'
        $("#" + nameOfDiv).on('shown.bs.collapse', function () {
            $.cookie(nameOfDiv, "true"); // this is a cookie.  named the same as the control (poor practice) for brevity 
        });
        // when the div is collapsed, remove the same cookie
        $("#" + nameOfDiv).on('hidden.bs.collapse', function () {
            $.removeCookie(nameOfDiv);
        });

        // on page load, show or hide the div (and stylized the header) according to the cookie (if it exists)
        var showDiv = $.cookie(nameOfDiv);
        if (showDiv != null) {
            $("#" + nameOfDiv).addClass("in");                      // The div to show
            $("#" + nameOfHeader).removeClass("collapsed");         // The header to stylize as expanded
        }
    };
</script>

<script language="javascript" type="text/javascript">
    $(document).ready(
        retainDivCollapsedState("divName", "divHeaderName")
    );
</script>

Upvotes: 2

Ravimallya
Ravimallya

Reputation: 6610

In Bootstrap 3.x.x you have to use the following script to save the last open state in cookies.

HTML Markup

<div class="panel-group" id="accordion">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">Collapsible Group
                    Item #1 </a>
            </h4>
        </div>
        <div id="collapseOne" class="panel-collapse collapse in">
            <div class="panel-body">
                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson
                ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food
                truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put
                a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim
                keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
                Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
                raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
                labore sustainable VHS.
            </div>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">Collapsible Group
                    Item #2 </a>
            </h4>
        </div>
        <div id="collapseTwo" class="panel-collapse collapse">
            <div class="panel-body">
                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson
                ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food
                truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put
                a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim
                keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
                Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
                raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
                labore sustainable VHS.
            </div>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree">Collapsible
                    Group Item #3 </a>
            </h4>
        </div>
        <div id="collapseThree" class="panel-collapse collapse">
            <div class="panel-body">
                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson
                ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food
                truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put
                a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim
                keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
                Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
                raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
                labore sustainable VHS.
            </div>
        </div>
    </div>
</div>

Jquery

  $(document).ready(function () {
        //when a group is shown, save it as the active accordion group
        $("#accordion").on('shown.bs.collapse', function () {
            var active = $("#accordion .in").attr('id');
            $.cookie('activeAccordionGroup', active);
          //  alert(active);
        });
        $("#accordion").on('hidden.bs.collapse', function () {
            $.removeCookie('activeAccordionGroup');
        });
        var last = $.cookie('activeAccordionGroup');
        if (last != null) {
            //remove default collapse settings
            $("#accordion .panel-collapse").removeClass('in');
            //show the account_last visible group
            $("#" + last).addClass("in");
        }
    });

Upvotes: 18

ws8
ws8

Reputation: 107

Thanks for this, found it very helpful, but if you are using Bootstrap 3 & latest jquery, this works:

$("#accordion").on('shown.bs.collapse', function()
{
   ...
});

Hope this saves others some time....

Upvotes: 0

Devindra
Devindra

Reputation: 139

I tried the technique suggested above and it worked for me (sort of) but calling .collapse("show") seemed to break the accordion toggle behavior in some instances. Opening first panel would leave previously opened panel in open state. I got round this with jQuery by adding class "in" instead:

$(document).ready(function() {
    var last=$.cookie('activeAccordionGroup');
    if (last!=null) {
        //remove default collapse settings
        $("#accordion .panel-collapse").removeClass('in');
        //show the account_last visible group
        $("#" + last).addClass("in");
    }
});

Otherwise, thanks davidkonrad putting me on right track.

Upvotes: 3

davidkonrad
davidkonrad

Reputation: 85578

You can very easily solve this by a cookie. There is a lot of simplified libraries, like https://github.com/carhartl/jquery-cookie as I use in the example below :

<script src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>

add the following code to a script section (#accordion2 refers to the modfied twitter bootstrap example, I list afterwards)

$(document).ready(function() {
    var last=$.cookie('activeAccordionGroup');
    if (last!=null) {
        //remove default collapse settings
        $("#accordion2 .collapse").removeClass('in');
        //show the last visible group
        $("#"+last).collapse("show");
    }
});

//when a group is shown, save it as the active accordion group
$("#accordion2").bind('shown', function() {
    var active=$("#accordion2 .in").attr('id');
    $.cookie('activeAccordionGroup', active)
});

And you are done! Here a modified version of the example at http://twitter.github.com/bootstrap/javascript.html#collapse with clickable links, when you go back - the last shown accordion group opens up automatically

<div class="accordion" id="accordion2">
  <div class="accordion-group">
    <div class="accordion-heading">
      <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne">
        Collapsible Group Item #1
      </a>
    </div>
    <div id="collapseOne" class="accordion-body collapse in">
      <div class="accordion-inner">
        Link : <a href="http://google.com">google.com</a>
      </div>
    </div>
  </div>
  <div class="accordion-group">
    <div class="accordion-heading">
      <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo">
        Collapsible Group Item #2
      </a>
    </div>
    <div id="collapseTwo" class="accordion-body collapse">
      <div class="accordion-inner">
        Link : <a href="http://stackoverflow.com">stackoverflow.com</a>
      </div>
    </div>
  </div>
  <div class="accordion-group">
    <div class="accordion-heading">
      <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseThree">
        Collapsible Group Item #3
      </a>
    </div>
    <div id="collapseThree" class="accordion-body collapse">
      <div class="accordion-inner">
        Link : <a href="http://cryptozoologynews.blogspot.com/">cryptozoology news</a>
      </div>
    </div>
  </div>
</div>

Upvotes: 30

Related Questions