Search code examples
jquerycssjquery-animatemouseovermouseout

jQuery - Mouseout on Animated DIV


I'm trying to put together an animated drop-down menu of my own in jQuery but am getting weird results. I have a container wrapping a button DIV and a menu DIV, and the idea was to have (on mouseover) both the container DIV and menu DIV scale in height with the menu DIV getting a CSS {'display', 'block'}. On mouseout of the container DIV (which is supposed to have scaled in height to contain both the button and menu DIVs) I wanted the DIVs to scale back to their original heights and the menu DIV to get a CSS {'display','none'}.

The problem now is that after everything scales up, instead of scaling back on mouseout of the supposedly scaled-up container (height: 300px), the scaling begins after mousingout of the container's original height (height: 100px), not the new one.

Here's the code:

$('.container').mouseover(function(){
    $('.bob').css('display','block');
    $('.bob').animate({height: '200px'});
    $(this).animate({height: '300px'});
});

$('.container').mouseout(function(){
    $('.bob').animate({height: '0'},
            function(){
            $('.bob').css('display','none');
            });
    $(this).animate({height: '100px'});
});

Solution

  • You probably need to use the on event to get the "live" .container element in its changed state. I also added the stop() function to stop the animation in case it was not finished before you mouseout/mouseover again.

    $(document).on('mouseover', '.container', function(){
        $('.bob').css('display','block');
        $('.bob').stop(true, false).animate({height: '200px'});
        $(this).stop(true, false).animate({height: '300px'});
    
    });
    
    
    
    $(document).on('mouseout', '.container', function(){
        $('.bob').stop(true, false).animate({height:0},
             function(){
                $('.bob').css('display','none');
             });
        $(this).stop(true, false).animate({height: '100px'});
    });
    

    EDIT: as requested here an explanation:

    This is like using the (now deprecated) live() function in JQuery which listened for changed dom elements or even elements added to the dom at a later time by js. If you only use $('.container').mouseover() it will listen for the dom element in its state as was on page load - which is only 100px high. It won't "realize" that the element has changed.

    The stop function is there so that any animation of the element going on right at the moment ist stopped before the new animation starts.

    http://api.jquery.com/on/

    http://api.jquery.com/stop/