DEV Community

[Comment from a deleted post]
Collapse
 
alephnaught2tog profile image
Max Cerrina • Edited

Quick sloppy demo (HTML etc included for demo purposes)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Session Demo</title>
</head>
<body>
    <p>
        When this page first loads, the first time you open it before clicking
        any buttons--the background is white.
    </p>
    <p>
        When you click red or green, then refresh the page, the color changes
        to that. If you close the tab entirely and open a new
        tab and open the url again--white again.
    </p>
    <p>
        If you hit the yellow button and refresh, it's yellow. If you close
        the tab like before, do a new one, open the page again--yellow!
    </p>
    <p>If you do yellow then green or red, and refresh, green or red
       wins--until you close that tab and reopen it, even close the browser
       and reopen it, and then it will be yellow... because you picked
       yellow!</p>
    <button onclick="pickRed()"
            style="background-color: red; color: white;">Red!
    </button>
    <button onclick="pickGreen()"
            style="background-color: green; color: white;">Green!
    </button>
    <button onclick="setLocalStorageToYellow()"
            style="background-color: yellow;">Set localstorage to yellow
    </button>
    <script>
        if (sessionStorage.getItem("chosenBackgroundColor") !== null)
        {
            document.body.style.backgroundColor =
                    sessionStorage.getItem("chosenBackgroundColor");
        }
        else if (localStorage.getItem("localBackgroundColor") !== null)
        {
            document.body.style.backgroundColor =
                    localStorage.getItem("localBackgroundColor");
        }


        // functions!
        function pickRed()
        {
            sessionStorage.setItem("chosenBackgroundColor", "red");
        }

        function pickGreen()
        {
            sessionStorage.setItem("chosenBackgroundColor", "green");
        }

        function setLocalStorageToYellow()
        {
            localStorage.setItem("localBackgroundColor", "yellow");
        }
    </script>
</body>
</html>