Greg
Greg

Reputation: 11

How do I add a fade in on click to a javascript dropdown?

I was using this: https://gist.github.com/nguyenning/f99b38ec9ccdf3b73732 and easily created a dropdown menu that works great but I want to have the menu Fade in and out when it is clicked. This is what I tried but the fadeIn is not working:

  $(function () {
  var $overlay = $('.overlay');
  var $toggle = $('.toggle-menu');
  var toggleOverlay = function (evt) {
    if (!$(evt.target).closest($overlay).length) {
        $overlay.addClass('hidden');
    } else {
        $(document).one('click', toggleOverlay) .fadeIn(1000);
   }
  }
  $toggle.click(function (evt) {
    evt.preventDefault();
    evt.stopPropagation();
    $overlay.toggleClass('hidden');
    $(document).one('click', toggleOverlay) .fadeIn(1000);
  });
});

Upvotes: 0

Views: 39

Answers (1)

Lam Pham
Lam Pham

Reputation: 58

The .slideToggle() function works. Is it what you want?

$(function () {
  var $overlay = $('.overlay');
  var $toggle = $('.toggle-menu');
  $toggle.click(function () {
    $overlay.slideToggle();
  });
});
.hidden {
  display: none;
}

.container {
  width: 300px;
  padding: 16px;
  margin: auto;
  position: relative;
  
  border-radius: 2px;
  border: 1px solid #ccc;
}

.overlay {
  position: absolute;
  border-radius: 2px;
  border: 1px solid #ccc;
}
  <div class="container">
    <a href="#" class="toggle-menu">Toggle Menu</a>
    <div class="overlay hidden">
      <ul>
        <li>
          <a href="#">Menu 1</a>
        </li>
        <li>
          <a href="#">Menu 2</a>
        </li>
        <li>
          <a href="#">Menu 3</a>
        </li>
      </ul>
    </div>
  </div>
  <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
  <script src="script.js"></script>

Upvotes: 1

Related Questions