Allenph
Allenph

Reputation: 2015

jQuery animation performing strangely due to excessive events?

I have a gallery on my site. Each image is a <div> which has a background image. The overflow is hidden, and I hide a caption div using margin. I then use the following jQuery to animate the captions when the mouse enters and leaves the picture <div>.

$(document).on("mouseenter", ".gallery-image", function(){
    $(this).children(".caption").dequeue();
    $(this).children(".caption").fadeIn({queue: false, duration: 500}).animate({marginTop: "350px"}, 500);
});
$(document).on("mouseleave", ".gallery-image", function(){
    $(this).children(".caption").dequeue();
    $(this).children(".caption").fadeOut({queue: false, duration: 500}).animate({marginTop: "400px"}, 500);
});

When I move the mouse in and out too fast weird things start to happen. The caption stays half-faded, or the caption simply stops appearing altogether.

The problem can be seen in this JSFiddle.

Why am I getting this unexpected behavior?

Upvotes: 0

Views: 22

Answers (1)

Sudharsan S
Sudharsan S

Reputation: 15393

Use .stop(true, true) to stop the pre queues of the animations

$(document).on("mouseenter", ".gallery-image", function(){
        $(this).children(".caption").stop(true,true).fadeIn({queue: false, duration: 500}).animate({marginTop: "350px"}, 500);
 });
    $(document).on("mouseleave", ".gallery-image", function(){
        $(this).children(".caption").stop(true,true).fadeOut({queue: false, duration: 500}).animate({marginTop: "400px"}, 500);
 });

Fiddle

Upvotes: 2

Related Questions