How to display/hide an element in Javascript

Asked

Viewed 139 times

2

I want to view and hide items from a list when the input is clicked. The code works if in css the ul tag has display:block, but not when it’s display:None; which is what I want.

Javascript:

<script>
    function fAbreGuias() {
    var vGuias = document.getElementById('guias');
        if (vGuias.style.display == "block"){ // se vGuias estiver escondido, exiba-o 
            vGuias.style.display = "none";
        }
        else{ // se vGuias for exibido, esconda-o
            vGuias.style.display = "block";
        }
    }
</script>

HTML:

<nav id="menu">
    <input type="image" src="_imagens/menuesboco.png" onclick="fAbreGuias()"/>
    <ul id="guias">
        <li>Guia 1</li>
        <li>Guia 2</li>
        <li>Guia 3</li>
    </ul>
</nav>

CSS

ul#guias li {
    display: block;
}

The page needs to start with the hidden list, but the code only works if it starts with the list being displayed.

2 answers

0

You can define a ". Hide" class in your CSS and then in javascript do:

    <script>
        function fAbreGuias() {
             var vGuias = document.getElementById('guias');
                  vGuias.addEventListener('click, function(){
                    vGuias.toggle("hide");
                    
                    //Esse método toggle ele coloca ou tira a classe no elemento html de acordo com o evento a qual foi atribuído na função
                  }
         }
    </script>
.hide{
  display:none;
}

0


So, your Javascript it’s right the mistake there is your Css, as you are picking up an element by id, you don’t have to take anything else:

function fAbreGuias() {
  var vGuias = document.getElementById('guias');
  if (vGuias.style.display == "block") { // se vGuias estiver escondido, exiba-o 
    vGuias.style.display = "none";
  } else { // se vGuias for exibido, esconda-o
    vGuias.style.display = "block";
  }
}
#guias {
  display: none;
}
<nav id="menu">
  <input type="image" src="_imagens/menuesboco.png" onclick="fAbreGuias()" />
  <ul id="guias">
    <li>Guia 1</li>
    <li>Guia 2</li>
    <li>Guia 3</li>
  </ul>
</nav>

  • Thank you very much! That was the problem. I just didn’t understand why it worked with the display: block; and not with the display:None;

  • So, honestly I don’t understand, it might be something to do with the dial nodes ul > #guias > li, something acts there that makes present the behavior.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.