Babanna Duggani
Babanna Duggani

Reputation: 727

Button Color not changing on toggle for multiple buttons

I have multiple buttons in webpage. But trying to change button color for single button on each click. My code is as below. But not working.... Any help?

<html>
<head>
<script type="text/javascript">
function toggleColor(id) {
if(document.getElementById(id).style.background !== 'rgb(255,0,0)') {
    document.getElementById(id).style.background = '#FF0000';

}
else  {
    document.getElementById(id).style.background = '#00FF00';
}
}
</script>
</head>
<body>
<button type="button" id="1" style="background-color:#00FF00;"  onclick="toggleColor(this.id)">1</button>
</body>

Upvotes: 2

Views: 1192

Answers (4)

guymid
guymid

Reputation: 1206

The main issue was just your comparison needed to include spaces. My example passes in the button so that you don't need to get the element again by ID.

Example JSBIN

HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <button type="button" id="1" style="background-color:#00FF00;"  onclick="toggleColor(this)">1</button>
</body>
</html>

JavaScript:

function toggleColor(el) {
if(el.style.background == 'rgb(0, 255, 0)') {
    el.style.background = '#FF0000';
}
else  {
    el.style.background = '#00FF00';
}
}

Upvotes: 0

Freeman Lambda
Freeman Lambda

Reputation: 3655

Your problem stands in the string comparsion

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

The actual value of the background, after setting it's color, is rgb(255, 0, 0)

Be carefull with the spaces inside the rgb()

Upvotes: 2

abcd
abcd

Reputation: 3210

This is working code. Your code is having error. No script tag, not valid if statement. Use this code it is working one.

<html>
<head>
<script>
window.toggle = true;
function toggleColor(id) {
console.log(document.getElementById(id).style.background);
console.log(document.getElementById(id).style.background.indexOf('rgb(0, 255, 0)'));
if(document.getElementById(id).style.background.indexOf('rgb(0, 255, 0)')>0)
    document.getElementById(id).style.background = '#FF0000';
else if(document.getElementById(id).style.background.indexOf('rgb(255, 0, 0)')>0)
    document.getElementById(id).style.background = '#00FF00';
}
</script>
</head>
<body>
<button type="button" id="1" style="background:#00FF00;"  onclick="toggleColor(this.id)">1</button>
</body>

Upvotes: 4

Deepak Kumar Jha
Deepak Kumar Jha

Reputation: 482

You are making syntax error in writing your code. put this code inside script tag.

 <script>
 function toggleColor(id) {
 if(document.getElementById(id).style.background !== 'rgb(255,0,0)') {
    document.getElementById(id).style.background = '#FF0000';

 }
 else  {
    document.getElementById(id).style.background = '#00FF00';
  }
 }
 </script>

Hope this solve your problem .

Thank you.

Upvotes: 1

Related Questions