Dropdown menu with javascript

0

I'm trying to make a dropdown menu just by changing <div's> with Js. Is there any way to use only function() to change <div's> ?
The only solution I found is to create a function() for each <div> that I want to hide / unhide but it would be too long the code.
What I've achieved so far is to hide and unhide a single <div> . Following:

JavaScript:

    function startmenu(){
            ex1.style.display = "none";
            }

    function abrefecha(){
            if(ex1.style.display == "none")
            {
                ex1.style.display = "block";
            }
            else
            {
                startmenu();
            } 
        }

HTML:

    <body>
    <h1>Exercícios JavaScript</h1>

    <a href="javaScript:abrefecha()"><h2> Exercício 1 </h2></a>
    <div id="ex1" style="display: none;">   
    </div>

    <a href="javaScript:abrefecha()"><h2> Exercício 2 </h2></a>
    <div id="ex2" style="display: none;">
    </div>      

    <a href="javaScript:abrefecha()"><h2> Exercício 3 </h2></a>
    <div id="ex3" style="display: none;">
    </div>
    ...
    
asked by anonymous 02.11.2017 / 23:40

2 answers

1

The if that is not complete and instead of the else call startMenu() should apply the style inverse, which is none :

ex1.style.display = "none";

You can also generalize the logic to any element, and receive this element the abrefecha function:

function abrefecha(elemento/*<--agora recebe o id do elemento a mostrar/esconder*/) {
  let ex = document.getElementById(elemento); //buscar elemento ao html com base no id

  if (ex.style.display == "none") {
    ex.style.display = "block";
  } else {
    ex.style.display = "none"; //agora no else volta a aplicar none
  }
}
<h1>Exercícios JavaScript</h1>

<a href="javascript:abrefecha('ex1')"><!--Agora passa o div a mostrar/esconder-->
  <h2> Exercício 1 </h2>
</a>
<div id="ex1" style="display: none;">Div1</div> <!--Coloquei conteudo nos divs-->

<a href="javascript:abrefecha('ex2')"><!--Agora passa o div a mostrar/esconder-->
  <h2> Exercício 2 </h2>
</a>
<div id="ex2" style="display: none;">Div2</div>

<a href="javascript:abrefecha('ex3')"><!--Agora passa o div a mostrar/esconder-->
  <h2> Exercício 3 </h2>
</a>
<div id="ex3" style="display: none;">Div3</div>

You can also simplify the abrefecha function with a ternary operator by doing:

function abrefecha(elemento) {
  let ex = document.getElementById(elemento);
  ex.style.display = ex.style.display=="none" ?"block":"none";
}
    
03.11.2017 / 00:25
0

Try:

$(document).ready(function() {
    $('#menu-icon').click(function() {
        $('.nav-menu ul').toggleClass('visible');
    });
});

<!-- my code -->
<div class="header-nav">
  <nav class="nav-menu">
    <ul>
        <li>Item 1</li>
        <li>Item 2</li> 
    </ul>
  </nav>

  <a href="#" id="menu-icon"></a>
</div>
    
02.11.2017 / 23:51