John Mike
John Mike

Reputation: 147

Why is this javascript code to change background color not working?

I want to change the background color ,when the user clicks the button, to the color he/she selected from the dropdown. Here's the html and javascript code for it.

<!DOCTYPE html>
<html>
    <head>
        <title>Change Color Demo</title>
        <script>
            function changeColor(){
                var selColor = document.getElementById("selColor");
                var color = selColor.value;
                document.body.style.backgroundColor = color;
            }
        </script>
    </head>
    <body>
        <form action="">
            <fieldset>
                <select id="selColor">
                    <option value="FFFFFF">White</option>
                    <option value="FF0000">Red</option>
                    <option value="FFCCFF">Orange</option>
                    <option value="FFFF00">Yellow</option>
                    <option value="00FF00">Green</option>
                    <option value="0000FF">Blue</option>
                    <option value="663366">Indigo</option>
                    <option value="FF00FF">Violet</option>
                </select>

                <input type="button" value="change color" onClick="changeColor()"/>
            </fieldset>
        </form>
    </body>
</html>

But it's not working for some reason. Please help.

Thanks

Upvotes: 0

Views: 2296

Answers (2)

Timur Zhilenkov
Timur Zhilenkov

Reputation: 69

The code is missing '#'. Just a tiny fix:

document.body.style.backgroundColor = "#"+color;

Upvotes: 1

Quentin
Quentin

Reputation: 943537

CSS colours using hex to represent RGB must start with a # character.

Upvotes: 3

Related Questions