How to keep the state of multiple <details> elements on page during a page refresh?

Viewed 131

I have a page that contains multiple details elements and I was interested in persisting the state of each details element through localStorage/sessionStorage. So if a user opens several of the details elements and then navigates to a new page and then back to the original page, the details elements that they originally opened would remain open. Any help on the best way to do this would be greatly appreciated. Thanks!

1 Answers

You can add id to each detail element, and save in localStorage the state of it using the event toggle.

Then on page load, run on localStorage and add open to each detail

See JSFiddle

(function() {
$('details').on('toggle', function(event) {
var id = $(this).attr('id')
var isOpen = $(this).attr('open')
console.log(id, isOpen)
window.localStorage.setItem('details-'+id, isOpen)
  })

function setDetailOpenStatus(item) {
  if (item.includes('details-')) {
var id = item.split('details-')[1];
var status = window.localStorage.getItem(item)
if (status == 'open'){
  $("#"+id).attr('open',true)
 }
   }
}

$( document ).ready(function() {
  for (var i = 0; i < localStorage.length; i++) {
setDetailOpenStatus(localStorage.key(i));
  }
});
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<details id='1'>
      <summary>System Requirements 1</summary>
      <p>Requires a computer running an operating system. The computer
      must have some memory and ideally some kind of long-term storage.
      An input device as well as some form of output device is
      recommended.</p>
    </details>
    <details id='2'>
      <summary>System Requirements 2</summary>
      <p>Requires a computer running an operating system. The computer
      must have some memory and ideally some kind of long-term storage.
      An input device as well as some form of output device is
      recommended.</p>
    </details>
    <details id='3'>
      <summary>System Requirements 3</summary>
      <p>Requires a computer running an operating system. The computer
      must have some memory and ideally some kind of long-term storage.
      An input device as well as some form of output device is
      recommended.</p>
    </details>

Related