RJorns
RJorns

Reputation: 281

JQuery Menu opens but then disappears

I have a menu that I have styled but when I click on the menu it flashes open, then immediately closes, and after a few clicks the whole thing up and disappears! Any reason as to why it is doing this?

Do I need to switch out .on with something else? I am using the latest version of jquery

Also, need to know if perhaps there is a better way to center the links?

JQuery Practice Navbar

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
<header>
  <div class="navbar-wrapper">
    <nav>
    <a class="burger-nav" href=""><i class="material-icons">menu</i></a>
    <ul class="navbar">
      <li class="nav-items"><a class="navlink" href="#">Home</a></li>
      <li class="nav-items"><a class="navlink" href="#">About</a></li>
      <li class="nav-items"><a class="navlink" href="#">Blog</a></li>
      <li class="nav-items"><a class="navlink" href="#">Contact</a></li>
    </ul>
    </nav>
  </div>
</header>

/* Mobile */


@media only screen and (max-width: 600px) {
  .burger-nav {
  border: 1px solid black;
  display: block;
  text-align: center;
  width: 100%;
  cursor: pointer;
  background: #404040;
}

.material-icons {
  color: white;
}

header nav ul {
  overflow: hidden;
  background: #505050;
  height: 0;
}

header nav ul.open {
  height: auto;
}

header nav ul li {
  list-style: none; 
  width: 100%;
  margin: 0;
  text-align: center;
}

header nav ul li a {
  color: #fff;
  padding: 0.625em;
  border-bottom: 1px solid #404040;
  display: block;
  margin: 0;
}
}



/* Normal */

@media only screen and (min-width: 600px) {
    .navbar {
    list-style: none;
    display: flex;
    justify-content: space-around;
    font-size: 1.5em;
    text-align: center;
    font-family: 'Poppins', sans-serif;
  }

  .navlink {
    text-decoration: none;
    color: inherit;
    text-transform: uppercase;
  }

  .navbar-wrapper {
    background-color: #949699;
    padding: 2em 0;
    box-shadow: inset -0.25em 0 0.25em 0 rgba(0, 0, 0, 0.1);
  }

  .navlink:hover {
    border-bottom: 1px solid lightgrey;
  }

  .burger-nav {
    display: none;
  }
}

$(document).ready(function() {

  $(".burger-nav").on('click', function() {
    $("header nav ul").toggleClass("open");

  });

});

Upvotes: 1

Views: 49

Answers (1)

Neelam Khan
Neelam Khan

Reputation: 1121

The problem was the height: 0 on your ul and the auto height set on your ul.open, instead of setting a height of 0, just show/hide using display: block and display: none.

Also the nav was disappearing because your href was empty for the burger nav link, I have updated the codepen with these changes.

header nav ul {
  overflow: hidden;
  background: #505050;
  display: none;
  /*height: 0;*/
}

header nav ul.open {
  /*height: auto;*/
  display: block;
}

https://codepen.io/anon/pen/jvmGPO

The nav now toggles as you would expect.

Upvotes: 1

Related Questions