Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!