Darren Bachan Darren Bachan - 6 months ago 18
HTML Question

Can't get menu to open properly after clicking on hamburger icon

I can't get a fiddle working but I have the issue live here.

When I click on the icon I get the menu to show for a brief second and then it disappears again. I thought with the javascript I have was saying that if I click on it, it'll stay open until you click on it again to close.

HTML

<div class="hamburger hamburger--spin" tabindex="0"
aria-label="Menu" role="button" aria-controls="navigation">
<div class="hamburger-box">
<div class="hamburger-inner"></div>
</div>
</div>

<nav id="menu">Content</nav>


Javascript

$(".hamburger").click(function() {
$("#menu").fadeIn("fast");
});
$(".hamburger").click(function() {
$("#menu").fadeOut("fast");
});

var $hamburger = $(".hamburger");
$hamburger.on("click", function(e) {
$hamburger.toggleClass("is-active");
// Do something else, like open/close menu
});


I have
display:none;
on
#menu
and when I click on the
.hamburger
it gives it
display:block;
I'm not sure what exactly is doing that. Also is there a way to combine this js?

Answer

You have binded two times the click event, the first one tries to show the element and then the second one tries to hide it while it's still showing, thus showing it always. Try this code

$(function() {
  $(".hamburger").click(function() {
    if ($("#menu").is(":hidden"))
      $("#menu").fadeIn("fast");
    else
      $("#menu").fadeOut("fast");
  });

  var $hamburger = $(".hamburger");
  $hamburger.on("click", function(e) {
    $hamburger.toggleClass("is-active");
    // Do something else, like open/close menu
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hamburger hamburger--spin" tabindex="0" aria-label="Menu" role="button" aria-controls="navigation">
  <div class="hamburger-box">
    <div class="hamburger-inner">INner</div>
  </div>
</div>

<nav id="menu">Content</nav>

Comments