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

280
Views
Why isn't the display toggling in Javascript?

I'm trying to do something where clicking one div would toggle the display of another div between block and none.

<div id="filtertop" onclick="toggleFilter()">Filter</div>
 function toggleFilter() {
      let x = document.getElementById("filter").style.display;
      if (x == "none") {
        x = "flex";
      }
      else{
        x = "none";
      }
        
    }

Currently, the code does nothing when I click on the div with id="filtertop"; the display should be changing to none.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You mean that?

function toggleFilter() {
  let x = document.getElementById("filter");
  if (x.style.display == "none") {
    x.style.display = "flex";
  } else {
    x.style.display = "none";
  }

}
<div id="filtertop" onclick="toggleFilter()">Filter</div>
<div id="filter">div with ID</div>

about 4 years ago · Juan Pablo Isaza Report

0

The issue with your code was already explained by @CherryDT within the comments.

Either you have to change your JS to:

function toggleFilter() {
  let x = document.getElementById("filter");
  if (x == "none") {
    x.style.display = "flex";
  } else {
    x.style.display = "none";
  }
}

The smarter and more modern solution would be to use classList.toggle('class-name') as shown in the example below. That applies a CSS class and toggles. Therefore you do not need to use an if / else statement.

function toggleFilter() {
  document.querySelector('.filter').classList.toggle('d-none');
}
.filter {
  display: flex;
}

.d-none {
  display: none;
}


/* for styling purpose only */
.filter {
  height: 50vh;
  background-color: red;
  grow: 1;
  margin-top: 20px;
}

#filtertop {
  font-size: 2em;
}
<div id="filtertop" onclick="toggleFilter()">Filter</div>

<div class="filter">Filter Element</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!