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

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

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 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