locked
JavaScript background color RRS feed

  • Question

  • User1298215938 posted
    <select onchange="changeBG()" name="D1"> <option></option> <option value="red"></option> </select>
    <select id="bgchoice" onchange="changeBG()" name="D1">
    <option></option>
    <option value="red">Red</option>
    <option value="ivory">Ivory</option>
    <option value="pink">Pink</option>
    <option value="blue">Blue</option>
    <option value="Green">Green</option>
    </select>
    <p>
    <script type="text/javascript">
               function changeBG() {
                   var selectedBGColor = document.getElementById("bgchoice").value;
                   document.body.style.backgroundColor = selectedBGColor;
               }
            
           </script>
    </p>
    Friday, October 16, 2020 9:43 PM

All replies

  • User1298215938 posted

    the issue is when the screen refreshes the background color changes to the default color.

    Friday, October 16, 2020 9:44 PM
  • User475983607 posted

    the issue is when the screen refreshes the background color changes to the default color.

    And the expected behavior given the code.  You need to call changeBG again with with the correct background color in bgchoice. 

    Another option creating a design that stores the background color in a persistence store like a database table or user session.

    Friday, October 16, 2020 9:56 PM
  • User-1151440187 posted

    You have to store that bg color in the session. The browser supports local storage.

    Use this code:

    <!DOCTYPE html>
    <html>
    <body onload="onload()">

    <select id="bgchoice" onchange="changeBG()" name="D1">
    <option>Select color</option>
    <option value="red">Red</option>
    <option value="ivory">Ivory</option>
    <option value="pink">Pink</option>
    <option value="blue">Blue</option>
    <option value="Green">Green</option>
    </select>
    <p>
    <script type="text/javascript">
               function changeBG() {
                   var selectedBGColor = document.getElementById("bgchoice").value;
                   document.body.style.backgroundColor = selectedBGColor;
                   sessionStorage.setItem('colour', selectedBGColor);
               }
               
               function onload(){           
                        if (sessionStorage.getItem('colour')) {
                             document.body.style.backgroundColor = sessionStorage.getItem('colour');
                        }        

                }                   
           </script>
    </p>
    </body>
    </html>

    Hope you get it.

    Tuesday, October 27, 2020 4:45 AM