Search code examples
javascriptjavascript-objectsdom-events

Javascript using for web storage


Below is the code I have for my website I am trying to build. I keep going over the JavaScript to see if I have errors but can't find where I went wrong. I am trying to let users whom come to my site choose a background color from a drop down menu. I am also trying to make it so that when users come back to my website the background is still the same with the use of web storage. Here is my code below:

Code:

<script type="text/javascript">

    function setBackground()
    {
        localstorage.bgColor = document.getElementById("Color_list").value;
        document.body.style.backgroundColor = localStorage.bgColor;
    }

    function loadBackground()
    {
        if (localStorage.bgColor.length == 0)
        {
            localStorage.bgColor = "White";
        }
        else
        {
            document.body.style.backgroundColor = localStorage.bgColor;
            document.getElementById("Color_list").value = localStorage.bgColor;
        }

    }
</script>





<body onLoad="javascript: loadBackground();">

    <select id="Color_list">

        <option value="White">White</option>
        <option value="Gray">Gray</option>
        <option value="Orange">Orange</option>
        <option value="Purple">Purple</option>

    </select>

    <input type="button" value="Set Background color" onClick="javascript: setBackground();" />
</body>

Solution

  • You have 2 errors in this

    1. localStorage in place of localstorage inside setBackground method
    2. inside loadBackground method do this

      if (!localStorage.bgColor)
      {
          localStorage.bgColor = "White";
      }
      

    insead of

    if (localStorage.bgColor.length == 0)
        {
            localStorage.bgColor = "White";
        }
    

    Also, its better setItem and getItem while accessing localStorage's properties