Having menu visible for x number of seconds after hover has been removed?

Hi there,

I have the following fiddle:
https://jsfiddle.net/toolman/3yj409os/5/

I have a mega menu on desktop which works fine (ignore the gap as this isn’t there normally).

I would like the desktop mega menu on the “drop down menu” to remain open for 3 seconds after the user has hovered off the menu.

What would be the best way to do this?

I have seen these, but can’t seem to implement it.


and

Any help would be great.

Thanks

Hi @toolman, so where are you stuck?

I’ve tried changing this:

.megamenu .dropdown-menu {
  background: none;
  border: none;
  width: 100%;
	background: #f6f6f6
}

to this:

.megamenu .dropdown-menu {
  background: none;
  border: none;
  width: 100%;
	background: #f6f6f6;
    visibility: hidden;
  position: absolute;
 
  transition: 0.2s 1s;
}


.megamenu .dropdown-menu:hover {
  visibility: visible;
  transition-delay: 0s;
}

Ah okay… there are many missing semicolons in your CSS, but I wouldn’t mix the CSS-only solution with your JS approach in the first place – JS is the way to go IMHO as it is much more versatile and easier to address accessibility concerns. So what you’d have to do is setting a timeout for hiding the menu, rather than closing it directly; and also cancel that timeout if the menu is getting hovered again:

var DELAY = 1000
var timeout = null

function showMenu (element) {
  $(element).addClass('show').attr('aria-expanded', 'true')
  $(element).find('.dropdown-menu').addClass('show')
}

function hideMenu (element) {
  $(element).removeClass('show').attr('aria-expanded', 'false')
  $(element).find('.dropdown-menu').removeClass('show')
}

$('.dropdown')
  .mouseover(function () {
    showMenu(this)
    // Cancel the delayed closing of the dropdown
    window.clearTimeout(timeout)
  })
  .mouseout(function () {
    // Delay the closing of the dropdown to the given
    // amount of ms
    timeout = window.setTimeout(hideMenu, DELAY, this)
  })
2 Likes

@m3g4p0p Thank you very much, that worked perfectly. I will double check the CSS issues.

Thank you again!

1 Like

You can’t transition visibility. Either its hidden or its not. There is no half state.:slight_smile:

You would need to hide the menu off screen to hide it (absolute positioning) in order to add the transition effects. (You can’t use transition with display:none either because there is no mid state. Its either there or its not.)

Here’s an example with a 3 second delay on a dropdown menu.

However with the JS menu you are using you will need the JS version that @m3g4p0p kindly provided :slight_smile:

2 Likes

Thank you, yes I should have released that. Thank you I will have a play :slight_smile:

1 Like