Home > database >  I Cannot figure out this single script problem
I Cannot figure out this single script problem

Time:09-29

iv been trying to look for a way to save my div on a local storage so it doesn't show up again but I'm having trouble getting it to work

      <div>
        <!-- Button to hide  
      * may add js to locally save and not showup again--> <button type="button" class="btn btn-primary btn-sm"
          onclick="hidediv()">Understood</button>
        <script>
          function hidediv() {
            var x = document.getElementById("hidemeonclick");
            if (x.style.display === "none") {
              x.style.display = "block";
            } else {
              x.style.display = "none";
            }
            if (localStorage.getItem(hidediv) === 1) {
              // Local Storage to grab and locally hide div for {IPUSER}
              console.log("Function Failed")
            } else {
              console.log("div hidden")
              x.style.display === "none";
            }
          }
        </script>
      </div>

CodePudding user response:

Quite a few errors in your code. As others have mentioned, localStorage only stores strings so you shouldn't compare strict with a number. You're also using a === operator to set the style.display to none. Not really sure what you're trying to do here but this code will persistently hide a div based on the button being clicked

<div id="hidemeonclick">I'll be hidden</div>
<button id='btn' onclick="hidediv()">Click me to hide div</button>

if (localStorage.getItem('hidediv') === 'hide') {
  var x = document.getElementById("hidemeonclick");
  x.style.display = "none";
}

function hidediv() {
  var x = document.getElementById("hidemeonclick");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
  localStorage.setItem('hidediv', 'hide');
}

CodePudding user response:

You have to add a hidediv value to the localstorage using

window.localStorage.setItem("hideDiv",1,)

Then you need you write a function that can toggle the state of that hideDiv value (from 1 to 0, or true to false) in your localStorage when you click your button. And you also need a function that listens for that event, and applys

x.style.display = "none"
to your div.

This might be easier to do with a framework like React that has state management tools. I've used React for this before with darkmode for a project.

  • Related