Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda