Dropdown menu with javascript

Asked

Viewed 2,838 times

0

I’m trying to make a dropdown menu just by changing the <div's> with Js.
Is there any way to use just one function() to change the <div's>?
The only solution I’ve found is to create a function() for each <div> I wish to hide/re-export but the code would be too long.
What I’ve managed so far is to hide and re-experience a single <div>. Follows:

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

2 answers

1


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

ex1.style.display = "none";

You can also generalize logic to any element, by receiving this element the function abrefecha:

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>

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

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

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>

Browser other questions tagged

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