Katyoshah
Katyoshah

Reputation: 129

Change background image of website with select tag

I am learning JavaScript and I managed to change the background color:

<script>
     function changecolor(id,color) {
            id.style.backgroundColor=color;
     }
</script>


<div id="container">
     <p> Select Color to change background:</p>
     <select id="themenu" onchange="changecolor(container,themenu.value)">
          <option value="white"> </option>
          <option value="red">RED</option>
          <option value="blue">BLUE</option>
          <option value="green">GREEN</option>
     </select>
</div>

is there any other method to do it?

Upvotes: 2

Views: 581

Answers (4)

Tony Jose
Tony Jose

Reputation: 1664

I just called the parent element and its working perfectly.

onchange="changecolor(this.parentNode,themenu.value)"

Demo

Upvotes: 3

Code Lღver
Code Lღver

Reputation: 15603

Your javascript function should be this;

function changecolor(id,color){
  document.getElementById(id).style.backgroundColor=color;
}

Upvotes: 0

Sebastien C.
Sebastien C.

Reputation: 4833

You should simply refer to the current object (this), and then to it's parent node and it's value instead of using ids :

<script>
    function useValueAsParentColor(menu) {
        menu.parentNode.style.backgroundColor = menu.value;
    }
</script>

<div>
    <p> Select Color to change background:</p>
    <select onchange="useValueAsParentColor(this); ">
        <option value="white"> </option>
        <option value="red">RED</option>
        <option value="blue">BLUE</option>
        <option value="green">GREEN</option>
    </select>
</div>

Upvotes: 0

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

You might just got stuck in the syntaxes

<select id="themenu" onchange="changecolor(container,this.value)"> <!-- Change -->
 <option value="white"> </option>
 <option value="red">RED</option>
 <option value="blue">BLUE</option>
 <option value="green">GREEN</option>
</select>

this.value refers to the current object's selected value!

themenu.value also works fine you might just got stuck somewhere else!

Demo Update

Another Js Fiddle

Upvotes: 4

Related Questions