user1575698
user1575698

Reputation: 53

Toggling the background color of buttons

I have this portion of code which is intended to changed the color of input button every time I click it.

function colorchange(id) 
 {
   if(document.getElementById(id).style.background == '#FFFFFF')
  {
   document.getElementById(id).style.background = '#000000';
  }
 else
  {
   document.getElementById(id).style.background = '#FFFFFF';
  }
 }

<input type="button" id="k777" onclick="colorchange('k777');" style="background:#000000;"/>

However this does not work properly. It does change the color of the button from #000000 to #FFFFFF the first time I click it, but when I click it again it does not change back to #000000. It's still white. How do I fix this?

Upvotes: 2

Views: 2917

Answers (3)

helle
helle

Reputation: 11650

Try to solve it via css-classes

Here the HTML:

<style type="text/css">
    input.bg_1{
        background-color: #000";
    }
    input.bg_2{
        background-color: #fff;
    }
</style>
<input type="button" id="input_777" onclick="colorchange('input_777');" class="bg_1" value="hello world" />

the JS:

function colorchange(id){
    var item = document.getElementById(id);
    if(item.getAttribute('className') == 'bg_1'){
        item.setAttribute('className', 'bg_2');
    } else {
        item.setAttribute('className', 'bg_1');
    }
}

Maybe the Attribute is class in some browsers. You will have to check this. Btw. The code is not tested

Upvotes: 1

Some Guy
Some Guy

Reputation: 16210

That's because element.style.background returns values in the rgb format. Change your conditional if statement to check for the appropriate rgb values, and it should work fine.

Make that line this:

if(document.getElementById(id).style.background !== 'rgb(0, 0, 0)')

Demo, with your code fixed and cleaned up

Upvotes: 4

Lemex
Lemex

Reputation: 3794

function colorchange(id) 
 {

     var background = document.getElementById(id).style.background;

     if(background === "rgb(255,255,255)")
     {
     document.getElementById(id).style.background = "rgb(0,0,0)";
     }
     else
     {
        document.getElementById(id).style.background = "rgb(255,255,255)"; 
     }

 }

Because its RGB values,

Its working here http://jsfiddle.net/nE8SW/

Upvotes: 0

Related Questions