1

I need to edit this javascript that controls the slider menu, to keep slider menu current toggle position after page refresh

I've searched 2 dozen solutions on the webs without result

I expect the menu to stay open or closed based on current toggle after page refresh but I can't figure out how to add the correct code to the script

    <script>
function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
    document.body.style.backgroundColor = "rgb(0,0,0)";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
    document.body.style.backgroundColor = "black";
}
</script>
Chaz Steiner
  • 447
  • 2
  • 5
  • 11

1 Answers1

1

Based on Cuong le Ngoc's comment, you can do something like this. This code should be run when the page is loaded:

 var key = "menuState";

    try
    {
        /*Determine if the menu was closed, or if element does not exist in localstorage*/
        var menuOpen = localStorage.getItem(key);
        if (menuOpen === null || menuOpen === 'FALSE')
        {
            closeNav();                  //Close the menu.     
        }
        else
        {
             openNav();                  //Otherwise, the menu was open. Open it.
        }

    }
    catch (ex)
    {
        console.log("Unable to access local storage to update menu state. " +ex.message);
    }

Now in your openNav() and closeNav(), you can see the local storage value for the menu status element.

   function openNav() {
   document.getElementById("mySidenav").style.width = "250px";
   document.body.style.backgroundColor = "rgb(0,0,0)";

   localStorage.setItem(key, 'TRUE');        //Mark menu as open.
   }

  function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
    document.body.style.backgroundColor = "black";

    localStorage.setItem(key, 'FALSE');    //Mark menu as closed.
   }
Oloff Biermann
  • 706
  • 5
  • 18
  • 1
    i think it's not necessary to use boolean here, string is enough so you won't need to use `JSON.stringify()` – Cuong Le Ngoc Jul 06 '19 at 02:41
  • @CuongLeNgoc That's true. I've updated the answer so that the element is stored and accessed directly as a string, without having to use `JSON.stringify()` or `JSON.parse()` – Oloff Biermann Jul 06 '19 at 06:19
  • You guys are great, I need to learn more because I'm not sure how to apply this. For dummies, what is local host? – Chaz Steiner Jul 07 '19 at 19:53
  • @ChazSteiner Typically, `localhost` refers to your local machine. If you are using your own computer as the server, then that is what `localhost` usually refers to. This name is then resolved to IPv4 address 127.0.0.1., which is called the loopback address. Using `localhost` allows you to access something (e.g. html file) hosted on the server, from the server itself. But remember, this has nothing to do with `localStorage`. – Oloff Biermann Jul 08 '19 at 20:26