Search code examples
javascriptjquerylocal-storagesession-storage

Hide and Show elements across multiple pages


Is there a way to save the state of an element across multiple pages? Maybe using session or local storage perhaps?

Functionality like this is what I want to achieve. But I want it to remember what is shown and hidden upon exiting and returning to the page.

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
This is my DIV element.
</div>

<script>
function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}
</script>

Solution

  • To achieve expected result, use below option localStorage and onload function

    1. Use locaStorage.setItem and localStorage.getItem to set and fetch values from localstorage

    2. Use onload function on body to set display from the localstorage

    function myFunction() {
        var x = document.getElementById("myDIV");
      console.log(x.style.display)
        if (x.style.display === "none") {
          localStorage.setItem('display','block')
            x.style.display = "block";
        } else {
            localStorage.setItem('display','none')
            x.style.display = "none";
        }
      console.log(localStorage)
    }
    
    function checkDisplay(){
          var x = document.getElementById("myDIV");
          x.style.display = localStorage.getItem('display');
    }
    <body onload="checkDisplay()">
    <button onclick="myFunction()">Try it</button>
    
    <div id="myDIV">
    This is my DIV element.
    </div>
      
      <body>

    code sample - https://codepen.io/nagasai/pen/BxabBz