简体   繁体   中英

How to save the state of accordion using localStorage

I wanted to save the state of the accordion and keeping it after the page refresh.

So far here is script.

 <script>
    $(document).ready(function () {
    $('table').accordion({
     header: '.category',
     collapsible: true,
     active: localStorage.getItem('accordion-active')||false
     });
});
  window.onload = function(){
  localStorage.setItem('accordion-active',$('table').accordion('option','active'));
};
 </script>

JFIDDLE

but it seems I couldn't make it work. Any suggestions?

You would do that by storing the index of the current active accordion in the acivate event, and then use it in the active option on pageload

$(document).ready(function () {
     $('table').accordion({
         header: '.category',
         collapsible: true,
         activate: function(e, ui) {
             localStorage.setItem('accordion-active', $(this).accordion( "option", "active" ));
         },
         active: +localStorage.getItem('accordion-active')
     });
});

FIDDLE

$(document).ready(function () {
 $('table').accordion({
     header: '.category',
     collapsible: true,
     activate: function(e, ui) {
         localStorage.setItem('accordion-active', $(this).accordion( "option", "active" ));
     },
     active: parseInt(localStorage.getItem('accordion-active'))
 });
});

Use parseInt(localStorage.getItem('accordion-active')) for active option if you want all of the tables in the accordion to load as collapsed initially.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM