Andy
Andy

Reputation: 7826

jQuery hover problem when moving mouse too quickly between elements

I have the following html repeated many times on a page:

<div class="outer">
    outer
    <div class="inner">
        inner
   </div>
</div>

and have this jQuery:

$('.inner').hide();
$('.outer').hover(function(e) {
    $(this).children('.inner').show("slide", {
        direction: "right"
    }, 1000);
}, function(e) {
    $(this).children('.inner').hide("slide", {
        direction: "right"
    }, 1000);
});

As you can see here: http://jsfiddle.net/342q3/15/ moving the mouse slowly between the divs (waiting for the animation to complete) achieves the desired effect of displaying only one inner div at a time.

However if you move the mouse quickly between the divs, all the inner divs remain visible.

I've tried using the stop() function but without success. How can I prevent the inner divs from remaining open?

Upvotes: 3

Views: 3675

Answers (3)

dougajmcdonald
dougajmcdonald

Reputation: 20047

Animate() is the function you want, I have written my navigation system using this functiong with this kind of syntax:

$("your-selecter").hover(function() {   

    $(this).stop().animate({
        backgroundPosition: '0 0'
    }, 600);
    }, function() {
       $(this).stop().animate({
            backgroundPosition: '0 -100px'
       }, 600); 
    });
};

Obviously you'd not want to change the BG position in yours, you'd call you slide function in there, but it's this kind of concept.

Upvotes: 1

Niko
Niko

Reputation: 26730

If you stop the animation before you start the new one (sliding out) and use find instead of children (no idea why it doesn't work with children), it works as supposed:

$('.inner').hide();
$('.outer').hover(function(e) {
    $(this).find('.inner').stop(true, true).show("slide", {
        direction: "right"
    }, 1000);
}, function(e) {
    $(this).find('.inner').stop(true, true).hide("slide", {
        direction: "right"
    }, 1000);
});

http://jsfiddle.net/AVLdW/

Upvotes: 4

simoncereska
simoncereska

Reputation: 3043

try writing code with animation() that way you'll be able to stop() it anytime and set default styles.

Upvotes: 1

Related Questions