2

I have this code that makes menu items slide down and up. I want to add a timer so there is a delay in the slide down then back up.

$(function () {
    $("#menu").find("li").each(function () {
        if ($(this).find("ul").length > 0) {
            $(this).mouseenter(function () {
                $(this).find("ul").stop(true, true).slideDown();
            });
            $(this).mouseleave(function () {
                $(this).find("ul").stop(true, true).slideUp();
            });
        }
    });
});
2
  • 3
    What does this have to do with Java? What programming language is this? Commented Jul 8, 2012 at 19:31
  • 1
    I think you can use the following instead of each to add event listeners $("#menu ul li ul:not(:empty)").mouseenter(function(){...}) .mouseleave(function(){...}); Commented Jul 8, 2012 at 19:49

2 Answers 2

4

It appears like you're writing javascript with jQuery

jQuery has a built in .delay function for animation queues.

In your example, delaying the slidedown animation by 300 ms would look like

$(this).find("ul").stop(true, true).delay(300).slideDown();

See jQuery's delay

Sign up to request clarification or add additional context in comments.

Comments

0

A smart approach would be to add a hover intent to wait before triggering mouseleave:

jsBin demo

$("#menu").find("li:has(ul)").on('mouseenter mouseleave',function( e ){
     var $UL = $(this).find('ul');
     if(e.type==='mouseenter'){
          clearTimeout( $(this).data('wait') );
          $UL.stop(1,1).slideDown();
     }else{            
          $(this).data('wait', setTimeout(function(){
              $UL.stop().slideUp();
          },180) );     
     } 
});
  • instead of using if ($(this).find("ul").length > 0) { just use: ("li:has(ul)")
    to trigger your events only on li elements that has ul as children.
  • add an event callback e for the mouseenter mouseleave.
  • if the e event == mouseenter ..... else is mouseleave.
  • Than clear the data attribute called 'wait' and slideDown the children ul
  • Now, leaving the original li element to reach the 'distant' ul we have to cross over a white space (demo) that will usually trigger immediately the 'slideUp()', but we set a timeout counter inside that li's data attribute that will wait ~180ms before running.
  • Reaching the 'distant' ul element - beeing a children of the timeouted 'li' we clear the timeout (step 1) 'retaining' the mouseenter state.

use ~180ms or how much you think is needed to reach with the mouse the 'distant' UL element

1 Comment

@user1510450 You're welcome! Hope I guessed well your needs. (Welcome to SO; make sure to read the FAQ and this: How to accept an answer )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.