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

118
Visualizações
how to activated new function after button clicked for three times

i want to add new function after i clicked the button 3 times and erase/remove the former function

html file:

<body> 
  <div id="background">
    <p>this background white, before</p>
  </div>
  <button class="btn-1">change color</button>
</body>

javascript:

const btn1 = document.querySelector(".btn-1") ;
const bg = document.getElementById("background")

const toRed = ()=>{
  bg.style.backgroundColor = "red";
}
const toBlue = ()=>{
  bg.style.backgroundColor = "steelblue";
}

btn1.addEventListener('click', toRed);

// i want this btn1 have function to clear function toRed and add toBlue instead after clicked 3 times

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

0

remove the event listener and add a new one when it was clicked three times:

const btn1 = document.querySelector(".btn-1");
const bg = document.getElementById("background");
var redClicked = 0;
const toRed = ()=>{
  bg.style.backgroundColor = "red";
  redClicked++;
  if (redClicked >= 3) {
    btn1.removeEventListener('click', toRed);
    btn1.addEventListener('click', toBlue);
  }
}
const toBlue = ()=>{
  bg.style.backgroundColor = "steelblue";
}

btn1.addEventListener('click', toRed);
<body> 
  <div id="background">
    <p>this background white, before</p>
  </div>
  <button class="btn-1">change color</button>
</body>

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