Levin
Levin

Reputation: 75

FadeToggle/SlideToggle only works once

I am trying to create a navigation drawer that fades out/fades in when clicked. In the jQuery code, I had made the navigation hide on load and when I click on the burger icon it fades in. However when I click on it again, it doesn't fade out.

I've had similar problems with the 'click' function before (in that the event takes place only the first time it was clicked) and I still can't figure out. Help would be greatly appreciated!

$(document).ready(function() {
  $('#topnav ul').hide()
  $('#burger').click(function() {
    $('#topnav ul').fadeToggle(300);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header id="title">
  <input type="checkbox" id="checkboxfornav">

  <nav id="topnav">   
    <label id="burger" for="checkboxfornav">
      <div id="topline"></div>
      <div id="midline"></div>
      <div id="botline"></div>
    </label>

    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">About</a></li>
      <li><a class="works" href="#">Works</a></li>
      <li><a class="news" href="#">News</a></li>
      <li><a href="#">Shop</a></li>
      <li><a href="#">Contact</a></li>
    </ul>
  </nav>
</header>

Upvotes: 1

Views: 193

Answers (2)

Levin
Levin

Reputation: 75

All of your answers were helpful! It was my own mistake lol. When the navigation fades in, it covers over my #burger(the navigation was was not fully opaque.) After playing around with the z-index, I managed to solve it. Thank you so much!

Upvotes: 0

Alexis
Alexis

Reputation: 5831

First the event listener was not on the checkbox, and when you put it on the checkbox the fadeToggle works.

$(document).ready(function() {
  $('#topnav ul').hide()
  $('#checkboxfornav').change(function() {
       $('#topnav ul').fadeToggle($(this).is(":checked"));
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header id="title">
  <input type="checkbox" id="checkboxfornav">

  <nav id="topnav">   
    <label id="burger" for="checkboxfornav">
      <div id="topline"></div>
      <div id="midline"></div>
      <div id="botline"></div>
    </label>

    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">About</a></li>
      <li><a class="works" href="#">Works</a></li>
      <li><a class="news" href="#">News</a></li>
      <li><a href="#">Shop</a></li>
      <li><a href="#">Contact</a></li>
    </ul>
  </nav>
</header>

Upvotes: 4

Related Questions