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

173
Visualizações
Why does my JS 'click event' only run once?

I created a click event that opens a previously 'hidden' div and closes it again once you click the same button.

However, it only runs once (one open and one close) - I'm at a loss to explain why it doesn't work if I click it again.

let readMore = document.getElementById('clickAbout');
let moreInfo = document.getElementById('about');
let changeSepa = document.getElementById('sepChange');


readMore.addEventListener('click', function(){
    changeSepa.style.height = '2rem';
    if (moreInfo.className == "") {
        moreInfo.className = "open";
        moreInfo.style.display = 'block';
    } else {
        
            moreInfo.style.display = 'none';
    }
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

this happens because you're checking if className == "", but you are modifying the className to be "open". On the second click it checks the className which is now "open" and goes to the else block. On the third click you expect for it to go into the first block but the className is still "open".

For an easy fix just change the className in the else block

else {
  moreInfo.className = "";  
  moreInfo.style.display = 'none';
}

Also i suggest you make use of the classList property on elements https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

using the class list it could look like this:

readMore.addEventListener("click", function () {
  changeSepa.style.height = "2rem";
  if (moreInfo.className == "") {
    moreInfo.classList.add("open");
    moreInfo.style.display = "block";
  } else {
    moreInfo.classList.remove("open");
    moreInfo.style.display = "none";
  }
});

Or even

readMore.addEventListener("click", function () {
  changeSepa.style.height = "2rem";
  moreInfo.classList.toggle("open");
  if (moreInfo.className == "") {
    moreInfo.style.display = "block";
  } else {
    moreInfo.style.display = "none";
  }
});

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