Delay dropdown menu from opening / closing using jQuery

Delay dropdown menu from opening / closing using jQuery

There are a few jQuery plugins out there that will manage your dropdowns and delays if the visitor accidentally mouses-off the element and keeps it open for xx milliseconds, so it doesn’t close instantly and the visitor doesn’t have to start again.

Here is a quick jQuery example to set a delay and kill it if needed.

var timeouts = [];
timeouts.open = [];
timeouts.close = [];

$('#my-element').hover(function() {
  // kill any close delay, we are hovering
  clearTimeout(timeouts.close['my-element']);
  // set small delay to open, to avoid opening on quick mouseover
  timeouts.open['my-element'] = setTimeout(function() {
    $('#my-element ul').slideDown('fast'); // slide down menu
  }, 300);
}, function() {
  // kill any open delay, we left element
  clearTimeout(timeouts.open['my-element']);
  // set delay to close, to avoid closing if quickly moused-out
  timeouts.close['my-element'] = setTimeout(function() {
    $('#my-element ul').slideUp('fast'); // slide down menu
  }, 300);
});

Comments are closed.