user2320500
user2320500

Reputation: 169

JQuery effect continues to iterate

I have a div within a parent div, that is normally hidden. When you hover over the parent div the child is then visible. I am using JQuery .toggle() to get this effect. The problem is that if you MouseIn and MouseOut really fast, repeatedly over the parent, the child div is toggled that many times. Is there a way to prevent this from happening, it is slowing down my page?

JSFIDDLE: http://jsfiddle.net/vY59g/1/

My JQuery:

$(document).ready(function() {
    $(".result").hover(function() {
        $(this).find(".result-user-facts").toggle("slow");
    });
});

Upvotes: 0

Views: 36

Answers (3)

Santino_Wu
Santino_Wu

Reputation: 53

If you want to make things better, just put div:.result-user-facts into an Variable if there only has one. Like this:

$(function (){
    var container = $(".result");
    var item = container.find(".result-user-facts").eq(0);
    $(".result").hover(function (){
        item.stop().toggle("slow");
    });
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388416

It is because the queuing nature of animations, every mouser enter and mouse leave operation queues a toggle operation. So if there are quick movement of mouse triggering the enter and leave events then even after the events are over the animations will keep happening.

The solution is to stop and clear previous animations before the toggle is called using .stop()

$(document).ready(function() {
    $(".result").hover(function() {
        $(this).find(".result-user-facts").stop(true, true).toggle("slow");
    });
});

Demo: Fiddle

Upvotes: 1

Use .stop(true,true)

Stop the currently-running animation on the matched elements.

Fiddle DEMO

$(document).ready(function() {
    $(".result").hover(function() {
        $(this).find(".result-user-facts").stop(true,true).toggle("slow");
    });
});

Upvotes: 0

Related Questions