Home > Enterprise >  How do I change the background color of button after clicking on it?
How do I change the background color of button after clicking on it?

Time:06-07

I need to change the background color of the button from dark to green

<button  id="btn" th:attr="onclick=|vote('${listAnswer.answer_id}',' 1')|"><i  ></i>UpVote</button> 


I tried to changed the button's background color from dark to green using following code. It does not work. Please help me

function vote(answerId,rateValue){

         alert(rateValue);

         axios.post('/saveRatings?answerId='   answerId   '&rateValue='   rateValue, {


         })
         .then(function(response){


      document.getElementById("btn").style.background-color='green';

         })

         }

CodePudding user response:

Insetead of

document.getElementById("btn").style.background-color='green';

user

document.getElementById("btn").style.backgroundColor = 'green';

CodePudding user response:

You can try this way

<button  id="btn" th:attr="onclick=|vote('${listAnswer.answer_id}',' 1')|"><i  ></i>UpVote</button>

JS

const btn = document.getElementById('btn');

btn.addEventListener('click', function onClick() {
  btn.style.backgroundColor = 'green';
  btn.style.color = '(Color whatever you want)';
});

CodePudding user response:

After you have clicked a button it's state becomes "active" and you can use css to change the color of the button to whatever you want. All you need to do is add a css rule using the ":active" selector. https://www.w3schools.com/cssref/sel_active.asp https://www.freecodecamp.org/news/css-button-style-hover-color-and-background/ Basically:

button:active { color: red; }  

CodePudding user response:

also instead of document.getElementById("btn").style.background-color you can use document.getElementById("btn").style['background-color']

  • Related