Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
How can I change an elements color when clicked a second time?

I'm working on a like button for a website I'm making and I have a simple piece of JavaScript that changes the color to red when it is clicked, but how can I make the color alternate so if you click it again it goes back to black than changes to red again if you click it another time etc.

const btn = document.getElementById("like");

btn.addEventListener('click', function onClick() {
    btn.style.color = 'crimson';
});

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Use the toggle method of the classList.

And, as a general rule, you should strive to avoid setting an "inline style" (element.style.xxx = xxx) as this creates a style for the element that can only be overridden by another inline style, leads to duplication of code, and therefore code that doesn't scale well. Instead, always try to work with CSS classes.

document.getElementById("like").addEventListener('click', function() {
    this.classList.toggle("active");
});
.active { color:crimson; }
<button id="like">Like</button>
about 4 years ago · Juan Pablo Isaza Relatório

0

you can follow this steps

First let's take a counter variable

let clickCount = 0;

Then add click event.Hare is your code:

const btn = document.getElementById("like");
    
            let clickCount = 0;
            btn.addEventListener("click", () => {
                clickCount++;
    
                if (clickCount > 1) {
                    btn.style.color = "red";
                }
            });
<button id="like">Like</button>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda