how to save collapsible button state to local storage

  css, html, javascript

i have 3 collapsible buttons that i want to save so it stays open/closed when they reload website

Exaple website

how can i make it save if it is open or closed in local storage? i would really appreciate if someone could show me some code that would do that

here is the code
style

.collapsible {
}

.content {
  max-height: 0;
  overflow: hidden;
}

body

<button type="button" id="collapsible" class="collapsible">collapsible1</button>
<div class="content">
text1
</div>
<br>
<button type="button" class="collapsible">collapsible2</button>
<div class="content">
text2
</div>
<br>
<button type="button" class="collapsible">Example iframe</button>
<div class="content">
<iframe width="560" height="315" src="https://www.youtube.com/embed/ThiCMd5kGbE" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

script

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.maxHeight){
      content.style.maxHeight = null;
    } else {
      content.style.maxHeight = content.scrollHeight + "px";
    } 
  });
}

Source: Ask Javascript Questions

LEAVE A COMMENT