Open and Close div using the same button with JavaScript

3

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

Ps: I would like that when you click on one of the menu links, the menu closes too.

I tried to use this 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>
    
asked by anonymous 16.03.2016 / 17:50

3 answers

5

Have you tried using 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><buttonid="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>
    
16.03.2016 / 18:04
1

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

$( ".hamburguer" ).toggle(function() {
   $(".menu").fadeIn();
}, function() {
   $(".menu").fadeOut();
});
    
16.03.2016 / 18:06
0

The response with toogle makes more sense than this work-arround that I posted. Live simplicity;)

I would use this artifice:

$("#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();
});
    
16.03.2016 / 18:03