JGuerra JGuerra - 7 months ago 12
HTML Question

Jquery Dropdown List not sliding up after mouse leave

So I was basically trying to create a drop-down list with jquery. I was successful in achieving but came across with a slight problem. Here's the code

HTML

<div class="dropdown_heading">
text
</div>
<div class="dropdown_container">
<div class="">
<a href="#">Competition1</a>
</div>
<div class="">
<a href="#">Competition2</a>
</div>
<div class="">
<a href="#">Competition3</a>
</div>

</div>


JQUERY

$(document).ready(function(){
$(".dropdown_heading").mouseenter(function(){
$(".dropdown_container").slideDown();
});

$(".dropdown_container").mouseleave(function(){
$(".dropdown_container").slideUp();
});
});


Once I hover over the dropdown_heading the dropdown shows-up and I'm able to navigate over it but the only way the it slides back up is if i actually have the cursor in the dropdown_container. If I try to slide it up removing the mouse from dropdown_heading, the dropdown is still visible. How would I be able to slide the submenu back up when the mouse leaves both div_container and div_heading?

I've tried to execute this function but therefore I am unable to navigate over the container. Thanks.

$(".dropdown_heading").mouseleave(function(){
$(".dropdown_container").slideUp();
});

Answer

You can try a timer based solution like

jQuery(function($) {
  var $target = $(".dropdown_container");
  $('.dropdown_heading').hover(function() {
    clearTimeout($target.data('hoverTimer'));
    $target.stop(true, true).slideDown(500);
  }, function() {
    var timer = setTimeout(function() {
      $target.stop(true, true).slideUp();
    }, 200);
    $target.data('hoverTimer', timer);
  });

  $target.hover(function() {
    clearTimeout($(this).data('hoverTimer'));
  }, function() {
    $(this).stop(true, true).slideUp();
  });
});
.dropdown_container {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown_heading">
  text
</div>
<div class="dropdown_container">
  <div class="">
    <a href="#">Competition1</a>
  </div>
  <div class="">
    <a href="#">Competition2</a>
  </div>
  <div class="">
    <a href="#">Competition3</a>
  </div>

</div>