Open and Close div using the same Javascript button

Asked

Viewed 7,717 times

4

I would like to make a menu appear and disappear (with fadein and fadeOut) using the same button, which in the case is a button with class ". hamburger" and I’m not sure how to do.

Ps: I would like that when clicking on one of the links in the menu, the menu also closes.

I tried to use that code :

$(".hamburger").click(function () {
    $(".menu").fadeIn(200);
});

$(".hamburger, .home, .meet, .services, .work, .about, .contact").click(function () {
    $(".menu").fadeOut();
});
<button class="hamburger" type="button"></button>

<nav class="menu">

  <ul>
    <li><a href="#inicio" class="inicio">Início</a></li>
    <li><a href="#a-empresa" class="empresa">A empresa</a></li>
    <li><a href="#art" class="art">ART's</a></li>
    <li><a href="#servicos" class="servicos">Serviços</a></li>
    <li><a href="#projetos" class="projetos">Projetos</a></li>
    <li><a href="#contato" class="contato">Contato</a></li>
  </ul>

</nav>

3 answers

5


Already tried to use slideToggle?

$('#hamburger').on('click', function() {
  $('#menu').slideToggle('slow');
});

$('.menu-link').each(function() {
  $(this).on('click', function() {
    $('#menu').slideToggle('slow');
  });
});
* {
  margin: 0 auto;
  padding: 0;
  box-sizing: border-box;
  font-family: sans-serif;
  list-style: none
}
#button {
  display: block
}
.menu {
  padding: 10px;
  border: 1px solid #f2f2f2;
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="hamburger" type="button">Menu</button>

<nav id="menu" class="menu">

  <ul>
    <li><a href="#inicio" class="menu-link inicio">Início</a>
    </li>
    <li><a href="#a-empresa" class="menu-link empresa">A empresa</a>
    </li>
    <li><a href="#art" class="menu-link art">ART's</a>
    </li>
    <li><a href="#servicos" class="menu-link servicos">Serviços</a>
    </li>
    <li><a href="#projetos" class="menu-link projetos">Projetos</a>
    </li>
    <li><a href="#contato" class="menu-link contato">Contato</a>
    </li>
  </ul>

1

Rather than .click(), you can use the function .toggle() jQuery. It would look like this:

$( ".hamburguer" ).toggle(function() {
   $(".menu").fadeIn();
}, function() {
   $(".menu").fadeOut();
});

0

The answer with toogle makes more sense than that work-arround I’ve come up with. Live Simplicity ;)

I would use this device:

$("#hamburger").click(function () {
    $(this).addClass('hamburguer-aberto');
    $(".menu").fadeIn(200);
});

$(".hamburger-aberto, .home, .meet, .services, .work, .about, .contact").click(function () {
    var botaoAbrir = $(".hamburguer-aberto");
    botaoAbrir.removeClass("hamburguer-aberto");
    $(".menu").fadeOut();
});

Browser other questions tagged

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