En este caso, mi botón Upvote es transparente y cuando hago clic en él, su color de fondo cambia de transparente a verde. Necesito hacer que este botón sea transparente cuando vuelva a hacer clic en él. Probé los siguientes códigos
function vote(){ var upVoteBtn = document.getElementById("upVote"); upVoteBtn.style.backgroundColor = "green"; upVoteBtn.style.color = "black"; } <button id="upVote" onclick=vote()>upVote</button>Como mencionó @CBroe, en lugar de agregar estilo en js, considere crear una clase con los estilos que necesita, toggle esta clase con un listener al hacer clic en el botón.
document.getElementById("upVote").addEventListener("click", () => { event.target.classList.toggle("upvoted") }) .upvoted{ background-color:green; } <button id="upVote">upVote</button>¡Prueba esto!
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 class="btn btn-outline-success" id="upVote" onclick=vote()>upVote</button> Si desea hacerlo transparente, simplemente use upVoteBtn.style.backgroundColor = "transparent"; en lugar de null . Al igual que a continuación.
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 class="btn btn-outline-success" id="upVote" onclick=vote()>upVote</button>¡Gracias y un saludo!
function vote(element){ element.classList.toggle("active"); } .btn.active{ background:green; color: #fff; } .btn{ background: transparent; color: black; } <button class="btn btn-outline-success" id="upVote" onclick=vote(this)>upVote</button> Solution of Problem
vote(this) enviar elemento de botóntoggle() usar para agregar y eliminar la clase activa.btn.active tiene clase activa o no