ItsOliMate
ItsOliMate

Reputation: 51

Html button colour change on click

hopefully this is a pretty easy one, I am building a web app using flask and python. On the front end of the app I am trying to get it to change the colour of the button pressed and revert any previous colour changes to other buttons so only the most recently selected button is a different colour.

The buttons are populated from an sql database so all use the same html line in a for loop. Below is the code I have currently:

Colour change script:

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

Button code:

 {% for item in categorydata %}
  <tr>
    <button id="{{item[0]}}" formtarget="Items" name="ItemCategory" value={{item[0]}} onClick="setColor('{{item[0]}}', '#101010')" style="color:black;height:50px;width:150px" >{{item[0]}}</button>
  </tr>
  {% endfor %}

Any ideas on how I can do this?

Upvotes: 1

Views: 612

Answers (2)

Anadkat Bhavik
Anadkat Bhavik

Reputation: 111

for this kind of problem you don't need to use JS. you have to do is use css :focus psuedo-class

for ex:

.btn:focus {
 background-color: red;
}

Upvotes: 2

Wassaf Shahzad
Wassaf Shahzad

Reputation: 313

So one way of doing this would be to add a class "modified" to the button pressed and remove class "modified" from the previously pressed button

CSS

modified {
    background-color: black;
}

Javascript

function calledOnClick(id){
    previousPressedButton =  document.getElementsByClassName("modified")[0]; //there should only be one item, check before hand if items exist ofcourse.
    previousPressedButton.classList.remove("modified")
    pressedButton = document.getElementById(id)
    pressedButton.classList.add("modified")
}

HTML

<button id=1 onclick="calledOnClick(this.id)"></button>

Upvotes: 0

Related Questions