Skip to content
Advertisement

How can I change background color of web page from drop down using javascript need this

I need help regarding JavaScript function code where I want to change the background-color of a web page from drop down list. When someone select any color from the list then it responds as same and change the background color of web page. I used the technique in JS is DOM. How we can done this. Here is my code for this task:-

<!DOCTYPE html>
<html>

<head>
  <script type="text/javascript">
    var change;

    function colour() {
      document.bgcolor = change.themes.val();
    }
    colour();
  </script>
</head>
<title>Best Themes</title>

<body>
  <form action="onchange(colour)" name="themes" method="post">
    <select name="colors">
    <option value="white" selected="select">White</option>
    <option value="black">Black</option>
    <option value="orange">Orange</option>
    <option value="green">Green</option>
    <option value="blue">Blue</option>
    <option value="skyblue">Sky Blue</option>
    <option value="pink">Pink</option>
    <option value="yellow">Yellow</option>
    <option value="mustard">Mustard</option>
    <option value="maroon">Maroon</option>
    <option value="magenta">Magenta</option>
    <option value="cyan">Cyan</option>
    <option value="gray">Gray</option>
    <option value="seagreen">Sea Green</option>
    <option value="chocolate">Chocolate</option>
    <option value="fuchsia">Fuchsia</option>
    <option value="gold">Gold</option>
    <option value="khaki">Khaki</option>
    <option value="silver">Silver</option>
    </select>
  </form>
</body>

</html>

Note-filename save as theme.html

Help please, thanks!

Advertisement

Answer

  1. You were not calling the onChange function
  2. The onChange function was set to the form and not the select
  3. You need document.body.style.backgroundColor to change the background color of the body
  4. You were using change.themes based on var change which is never used elsewhere and never set

function changeColor(el) {
  document.body.style.backgroundColor = el.value;
}
<select name="colors" onchange="changeColor(this)">
<option value="white" selected="select">White</option>
<option value="black">Black</option>
<option value="orange">Orange</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="skyblue">Sky Blue</option>
<option value="pink">Pink</option>
<option value="yellow">Yellow</option>
<option value="mustard">Mustard</option>
<option value="maroon">Maroon</option>
<option value="magenta">Magenta</option>
<option value="cyan">Cyan</option>
<option value="gray">Gray</option>
<option value="seagreen">Sea Green</option>
<option value="chocolate">Chocolate</option>
<option value="fuchsia">Fuchsia</option>
<option value="gold">Gold</option>
<option value="khaki">Khaki</option>
<option value="silver">Silver</option>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement