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

284
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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