Home > Software design >  How to change a button's color when clicked on it and change it back to its original color when
How to change a button's color when clicked on it and change it back to its original color when

Time:06-10

In this case, my Upvote button is transparent, and when I click on it, its background color changes from transparent to green. I need to make this button transparent when I click on it again. I tried the following codes

<button  id="upVote" onclick=vote()>upVote</button> 
 function vote(){

        var upVoteBtn = document.getElementById("upVote");
        upVoteBtn.style.backgroundColor = "green";
        upVoteBtn.style.color = "black";
}
                      

CodePudding user response:

As @CBroe mentioned, instead of adding style in js, consider making a class with styles you need, toggle this class with a listener on button click.

document.getElementById("upVote").addEventListener("click", () => {
  event.target.classList.toggle("upvoted")
})
.upvoted{
  background-color:green;
}
<button id="upVote">upVote</button>

CodePudding user response:

Try this!

var btnToggle = true;
var upVoteBtn = document.getElementById("upVote");

function vote(){
    if (btnToggle){
        upVoteBtn.style.backgroundColor = "green";
        btnToggle = false;
    } else{
        upVoteBtn.style.backgroundColor = null;
        btnToggle = true;
    }
}
<button  id="upVote" onclick=vote()>upVote</button>

If you want to make it transparent, then simply use upVoteBtn.style.backgroundColor = "transparent"; instead of null. Just like below.

var btnToggle = true;
var upVoteBtn = document.getElementById("upVote");
upVoteBtn.style.backgroundColor = "transparent";

function vote(){
    if (btnToggle){
        upVoteBtn.style.backgroundColor = "green";
        btnToggle = false;
    } else{
        upVoteBtn.style.backgroundColor = "transparent";
        btnToggle = true;
    }
}
<button  id="upVote" onclick=vote()>upVote</button>

Thanks and best regards!

CodePudding user response:

 function vote(element){
        element.classList.toggle("active");
}
                      
.btn.active{
  background:green;
  color: #fff;
}
.btn{
  background: transparent;
  color: black;
}
<button  id="upVote" onclick=vote(this)>upVote</button> 


Solution of Problem

  • vote(this) send element of button
  • toggle() use to add and remove active class
  • .btn.active check button have active class or not

CodePudding user response:

The OP should make use of the Element.classList's toggle method. In addition the OP should feel encouraged to drop inline event handling in favor of using the selector API together with EventTarget.addEventListener.

function toggleVotingState({ currentTarget }) {
  currentTarget.classList.toggle('voted');
}
document
  .querySelector('#upVote')
  .addEventListener('click', toggleVotingState);
.voted {
  color: black;
  background-color: green;
}
<button  id="upVote">upVote</button>

  • Related