2

I have three buttons. I would like them to change colour when pressed, and back to no colour when pressed again.

I found this code on stackoverflow that allows me to almost do it however, it only works on one button, the other two are not affected.
Also, when I pressed one of the other two buttons, the first button changes colour. I tried changing ID's on the buttons, adding another script with different getElementById() ID's but nothing works.

Do I need more than one function to achieve what I want?

The code I am using is below.

var count = 1;
function setColor(btn, color) {
  var property = document.getElementById(btn);
  if (count == 0) {
    property.style.backgroundColor = "#FFFFFF";
    count = 1;
  } else {
    property.style.backgroundColor = "#E68352";
    count = 0;
  }
}
<head>
  <link rel="stylesheet" type="text/css" href="styles/main.css"/>
</head>
<body>
  <input type="button" id="button" value = "A-D" style= "color:black" onclick="setColor('button', '#101010')";/>
  <input type="button" id="button" value = "E-H" style= "color:black" onclick="setColor('button', '#101010')";/>
  <input type="button" id="button" value = "E-H" style= "color:black" onclick="setColor('button', '#101010')";/>
</body>

5
  • IDs should be unique! Commented Feb 16, 2017 at 14:44
  • SO I should have three different functions and three buttons with different IDs? Commented Feb 16, 2017 at 14:46
  • No. Pass (this) and you have access to the clicked button regardless of ID or class Commented Feb 16, 2017 at 14:46
  • No, just one function but call it with different IDs! Commented Feb 16, 2017 at 14:47
  • Not exactly duplicate as OP is using style instead of class. stackoverflow.com/questions/14615712/… Commented Feb 16, 2017 at 14:59

8 Answers 8

2

Usually, when you write inline event handler you may take advantage of:

  • this: current element: When code is called from an in–line on-event handler, its this is set to the DOM element on which the listener is placed:
  • event: event element object

Therefore, change:

onclick="setColor('button', '#101010')"

with:

onclick="setColor(this, event, '#101010')"

So your code can be rewritten as:

function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? 'rgb(' +
        parseInt(result[1], 16) + ', ' +
        parseInt(result[2], 16) + ', ' +
        parseInt(result[3], 16) + ')'
     : null;
}


function setColor(btnEle, evt, color) {
    if (btnEle.style.backgroundColor == hexToRgb("#E68352")) {
        btnEle.style.backgroundColor = "#FFFFFF"
    }
    else {
        btnEle.style.backgroundColor = "#E68352"
    }
}
<input type="button" id="button1" value = "A-D" style= "color:black" onclick="setColor(this, event, '#101010')";/>
<input type="button" id="button2" value = "E-H" style= "color:black" onclick="setColor(this, event, '#101010')";/>
<input type="button" id="button3" value = "E-H" style= "color:black" onclick="setColor(this, event, '#101010')";/>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks gaetanoM. Lots of good answers but yours was most appropriate for my code and it worked out of the box. And I learned something new. Thanks to everyone else for their answers.
1

You should have uniques ID

You can use classList.toggle("yourClass") instead of using a count

var buttons = document.getElementsByClassName("button");
for (let i = 0, l = buttons.length; i < l; i++) {
  buttons[i].addEventListener('click', function() {
    buttons[i].classList.toggle('active');
  })
}
.active {
  background-color: #E68352 !important;
}

.button {
  background-color: #FFFFFF;
}
<input type="button" id="button1" class="button" value="A-D" />
<input type="button" id="button2" class="button" value="E-H" />
<input type="button" id="button3" class="button" value="E-H" />

Comments

0

Set a class on the buttons, and then loop through the buttons and add an event listener to each of them:

EDIT: I see you are using an onclick handler, which I didn't notice at first; so this answer might not be as useful as I thought. You should definitely use different IDs though if you use that approach.

<button class="button" ... >

var buttons = document.getElementsByClassName('button')
for (let i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', function() {
        // Do your button things.
    })
}   

Comments

0

IDs should be unique inside the document. Like this:

<input type="button" id="button1" value="A-D" style="color:black" onclick="setColor('button1', '#101010')" ;/>
<--                       here ^                                                      here ^               -->
<input type="button" id="button2" value="E-H" style="color:black" onclick="setColor('button2', '#101010')" ;/>
<--                       here ^                                                      here ^               -->
<input type="button" id="button3" value="E-H" style="color:black" onclick="setColor('button3', '#101010')" ;/>
<--                       here ^                                                      here ^               -->

<!DOCTYPE html>
<html>

<head>
  <script>
    var count = 1;

    function setColor(btn, color) {
      var property = document.getElementById(btn);
      if (count == 0) {
        property.style.backgroundColor = "#FFFFFF"
        count = 1;
      } else {
        property.style.backgroundColor = "#E68352"
        count = 0;
      }
    }
  </script>

  <link rel="stylesheet" type="text/css" href="styles/main.css" />
</head>

<body>

  <input type="button" id="button1" value="A-D" style="color:black" onclick="setColor('button1', '#101010')" ;/>
  <input type="button" id="button2" value="E-H" style="color:black" onclick="setColor('button2', '#101010')" ;/>
  <input type="button" id="button3" value="E-H" style="color:black" onclick="setColor('button3', '#101010')" ;/>

</body>

</html>

Comments

0

IDs need to be unique but you do not need them here

Give the buttons a class and use toggle the classList

window.onload=function() {
  var buts = document.querySelectorAll(".but");
  for (var i=0;i<buts.length;i++) {
    buts[i].onclick=function() {
      this.classList.toggle("clicked");
    }
  }
}
.but {background-color:black}
.clicked { background-color:#E68352; }
<input type="button" value="A-D" class="but" />
<input type="button" value="E-F" class="but" />
<input type="button" value="G-H" class="but" />

2 Comments

Few seconds faster hehe
6 seconds to be precise
0

dont use numbers, use this instead http://codepen.io/animhotep/pen/qRwjeX?editors=0010

var count = 1;

function setColor(btn, color) {
  if (count == 0) {
    btn.style.backgroundColor = "#FFFFFF"
    count = 1;
  }
  else {
    btn.style.backgroundColor = "#E68352"
    count = 0;
  }
}

Comments

0

Roberto, as Ibrahim correctly pointed out, the problem is that you are using the same ID for all buttons. When javascript executes this code:

var property = document.getElementById(btw);

it will always return the first element with the ID specified. One solution is choosing a different ID for each button and updating the corresponding onclick code. Another solution could be the one below, in which you do not need to specify IDs at all and the function setColor could be used for any element.

<!DOCTYPE html>
<html>
<head>
<script>
var count = 1;
function setColor(element, color) {
    if (count == 0) {
        el.style.backgroundColor = "#FFFFFF"
        count = 1;
    }
    else {
        el.style.backgroundColor = "#E68352"
        count = 0;
    }
}
</script>
<link rel="stylesheet" type="text/css" href="styles/main.css"/>
</head>

<body>
    <input type="button" value = "A-D" style= "color:black" onclick="setColor(this, '#101010')";/>
    <input type="button" value = "E-H" style= "color:black" onclick="setColor(this, '#101010')";/>
    <input type="button" value = "E-H" style= "color:black" onclick="setColor(this, '#101010')";/>
</body>
</html>

Note the use of the this variable as the first argument for setColor. In each of the buttons, the corresponding this will point to the element where it is defined.

Hope it helps.

Comments

0

You just need little bit of modification. See the working code.

function setColor(btn, color) {
  var elem = document.getElementById(btn);

  if (elem.hasAttribute("style")) {
    if (elem.getAttribute("style").indexOf("background-color:") == -1) {
          elem.style.backgroundColor = color;
    } else {
          elem.style.backgroundColor = "";
    }
  }
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" type="text/css" href="styles/main.css" />
</head>

<body>

  <input type="button" id="button1" value="A-D" style="color:black" onclick="setColor('button1', '#E68352')" ;/>
  <input type="button" id="button2" value="E-H" style="color:black" onclick="setColor('button2', '#E68352')" ;/>
  <input type="button" id="button3" value="E-H" style="color:black" onclick="setColor('button3', '#E68352')" ;/>

</body>

</html>

2 Comments

Thanks WitVault, this gets me closer however. after I click button1 and it changes colour, I then have to press button2 twice in order to change colour. Same for button3. The same issue comes up when I want the buttons to change back to no colour.
@Roberto you were using global variable for the check. Updated the answer please check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.