Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: how to properly use .stop() function?

On this page:

http://www.arvag.net/old/smsbox.de/

when you hover over "Informationen" and "Über ins", it shows a sub menu. When you move mouse away, it hides. Normally, I have problem with jQuery queuing every single hover I make, and then it just keeps on animating all those hovers. I tried to implement stop(), but I just can't get it to work properly.

This is the code I am using:

<script type="text/javascript">
    //<![CDATA[
    $(function(){
        $('#nav_menu > .center > ul > li').hover(function() {
            $(this).stop(true,true).children('ul').slideToggle('slow');
        }).click(function(){ 
            return false; 
        });
    });
    //]]>
</script>

Thanks!

like image 750
Gavrisimo Avatar asked Apr 02 '10 15:04

Gavrisimo


2 Answers

You need to .stop() in both directions to stop the queue, otherwise the mouseenter part of the hover keeps queuing it's animations. Also, since you're toggling, you can shorten it down like this:

$('#nav_menu > .center > ul > li').hover(function() {
   $(this).children('ul').stop(true,true).slideToggle('slow');
}).click(function(){ 
  return false; 
});

You would need the .stop() on the ul elements, since that's what's animating. Try this, you'll see it's a bit clunky still because it is resetting the animation instead of queuing. An alternative is to prevent the queue, like this using the :visible and :hidden selectors...I prefer this effect, but up to you :)

$('#nav_menu > .center > ul > li').hover(function() {
   $(this).children('ul:hidden').slideDown('slow');
}, function() {
   $(this).children('ul:visible').slideUp('slow');
}).click(function(){ 
  return false; 
});
like image 107
Nick Craver Avatar answered Sep 22 '22 02:09

Nick Craver


I believe you have to put stop(true,true) on the hover-over portion as well. It then interrupts other animations going on at the moment to execute its own, unless I'm mistaken.

    $('#nav_menu > .center > ul > li').hover(function() {
        $(this).stop(true,true).children('ul').slideToggle('slow');
    },function(){
        $(this).stop(true,true).children('ul').slideToggle('slow');
    }).click(function(){
        return false;
    });
like image 28
dclowd9901 Avatar answered Sep 21 '22 02:09

dclowd9901