Search code examples
jquerycssmenuhoverdelay

Delay the css:hover state on mouseout


I have a level 2 dropdown menu, where the mouse have to travel a pretty narrow corridor to keep the menu open, and if it gets off the track, the menu closes unexpectedly, this is frustrating. I want to make the menu not to close immediately, but with a delay.

it is a standard menu made with css like tis:

ul.menu li ul {
    display: none;
}
ul.menu li:hover ul {
    display:block;
}

I need when there is no more in hover state, the menu to still be visible for at least 0.5 seconds.

have tryed this, but it is not working:

<script>
$( ".menu li" ).mouseout(function() {
    $(".menu li ul").css("display: block");
    $(".menu li ul").css.setTimeout("display: none", 2000);
});
</script>

Solution

  • You can use a transition with a delay for the bit to make it stay visible on your hover out:

    .nested {
      pointer-events:none;       /* this is so it behaves like display none and mouse does not interact with child when hidden */
      opacity: 0;
      transition: opacity 0.1s;  /* change length to longer for a nicer fade */
      transition-delay: 1s;      /* fadeout won't happen for a second */
    }
    .hover:hover .nested {
      pointer-events: auto;
      opacity: 1;
      transition: opacity 0.1s;    /* fade in when hovered */
      transition-delay: 0s;        /* fade in immediately */
    }
    <div class="hover">
      hover
      <div class="nested">
      nested
      </div>
    </div>

    In the above, your ul would be the .nested and your parent li would be .hover