Search code examples
jqueryslidedownslideup

jQuery slide menu jittery behavior when rapid mouse hover


so I managed to create a setTimout slideUp/Down function for a menu that works great - but on certain occasions when the user hovers over links, and over their child links it rapidly slides up and down - I know this question is typical but I have tried different things unsuccessfully.

Here's a working demo - you can see if you mouse over the links the function goes nuts http://jsfiddle.net/eA2HL/2/

jQuery('.nav.mainmenu > li').each(function() {
    var t = null;
    var $this = jQuery(this);
    var result = jQuery('#result');
    $this.hover(function() {
        t = setTimeout(function() {
            if($this.find('ul').length > 0) {
                result.slideDown(200, function() {
                    if($this.is(':visible')) {
                        $this.find('ul').show();
                    }
                });
            }
            t = null;
        }, 300);
    }, function() {
        if (t) {
            clearTimeout(t);
            t = null;
        } else {
            $this.find('ul').hide(0);
            result.slideUp(333, function() {
                $this.find('ul').hide(0);
            });
        }
    });
});

Solution

  • Using .stop(1,1) (same as .stop( true , true )) will help to clear some animation buildups:

    jQuery('.nav.mainmenu > li').each(function() {
            var t = null;
            var $this = jQuery(this);
            var result = jQuery('#result');
            $this.hover(function() {
                t = setTimeout(function() {
                    if($this.find('ul').length > 0) {
                        result.stop(1,1).slideDown(200, function() {  // HERE
                            if($this.is(':visible')) {
                                $this.find('ul').show();
                            }
                        });
                    }
                    t = null;
                }, 300);
            }, function() {
                if (t) {
                    clearTimeout(t);
                    t = null;
                } else {
                    $this.find('ul').hide(0);
                    result.slideUp(333, function() { 
                        $this.find('ul').hide(0);
                    });
                }
            });
        });
    

    fiddle demo