Navigatron
Navigatron

Reputation: 2105

Image animation issue when using jQuery .animate()

I have an image animation problem that I need to fix. When the user hovers over the image, the image should increase in size. When the user moves out from the image, the image should return to its original size.

Problem: When the user moves over and out of the image very quickly, the image will expand and start distort itself, or change to a completely different size. It then continues animating while the mouse is not hovering over the image.

Here is a of the problem JSFiddle

I encountered the same problem using mouseover and mouseout events in the .on() method. Also while chaining those events together in the .on() method

HTML:

<div id="content">
<img id="foo" src="http://www.nasa.gov/images/content/297522main_image_1244_946-710.jpg"  alt="" title="" />

jQuery:

jQuery('#content').on("hover", '#foo', function (e) {
    var $img = jQuery(this);
    var $imgWidth = $img.width();
    var $imgHeight = $img.height();
    var $imgTop = $img.position().top;
    if (e.type == "mouseenter") {
        $img.animate({
            top: $imgTop - 20,
            width: $imgWidth * 1.2,
            height: $imgHeight * 1.2
        }, 200);
    } else if (e.type == "mouseleave") {
        $img.animate({
            top: $imgTop + 20,
            width: $imgWidth / 1.2,
            height: $imgHeight / 1.2
        }, 200);
    }
});

Upvotes: 2

Views: 667

Answers (1)

Blender
Blender

Reputation: 298076

You are getting the width and the height of the image every time you hover over it, even while the image is animating, so the current values aren't really the ones you want.

Instead, store the original values and work on those:

jQuery('img').load(function() {
    var $this = jQuery(this);

    $this.data({
        'orig-width': $this.width(),
        'orig-height': $this.height(),
        'orig-top': $this.position().top
    });
});

jQuery('#content').on("hover", '#foo', function(e) {
    var $this = jQuery(this);

    if (e.type == "mouseenter") {
        $this.stop().animate({
            top: $this.data('orig-top') - 20,
            width: $this.data('orig-width') * 1.2,
            height: $this.data('orig-height') * 1.2
        }, 200);
    } else if (e.type == "mouseleave") {
        $this.stop().animate({
            top: $this.data('orig-top'),
            width: $this.data('orig-width'),
            height: $this.data('orig-height')
        }, 200);
    }
});​

Demo: http://jsfiddle.net/TbDrB/5/

Upvotes: 4

Related Questions