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

139
Visualizações
Why is this function working on second click only?

I have a simple function that hides text on click. However it only works on the second click. I tried rewording the conditional statement but nothing has worked so far. jsfiddle https://jsfiddle.net/Montinyek/293hmpu1/18/

let btn = document.getElementById('btn');
let hello = document.getElementById('hello');

function test() {
  if (hello.style.display !== 'block') {
    hello.style.display = 'block';
  } else {
    hello.style.display = 'none';
  }
}

btn.addEventListener('click', test)
<div id='hello'>
  hello
</div>

<div id='btn'>
  button
</div>

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

0

At the start nothing has set the style so the test !==‘block’ will be true. And you then set the style to block so it needs another click to get it to none.

If you set things the other way round it will work because the style is not set to none so you then immediately set it to none.

The confusion often seems to arise because setting the style properties is not there initially, ie not set until you set them.

let btn = document.getElementById('btn');
let hello = document.getElementById('hello');

function test() {
  if (hello.style.display !== 'none') {
    hello.style.display = 'none';
  } else {
    hello.style.display = 'block';
  }
}

btn.addEventListener('click', test)
<div id='hello'>
  hello
</div>

<div id='btn'>
  button
</div>

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