Pier-Alexandre Bouchard
Pier-Alexandre Bouchard

Reputation: 5235

Resize Image to it's original dimension using jQuery Animation

I want to animate an image from 200 x 300px to its original size using jQuery.

I have this picture:

var imgHtml = "<img id='bigImg' src='" + bigSrc + "' alt='' style=\"height:200px; width:300px\"/>";
$("#divId").html(imgHtml);

And this jQuery code:

$("#bigImg").animate({
    height: "400px",
    width: "600px",
},500);

It works well, but I actually have to hardcode the future size. I would like to animate to the original size.

How can I do this ?

Upvotes: 1

Views: 1621

Answers (2)

Amar Palsapure
Amar Palsapure

Reputation: 9680

Try doing this

HTML

<div id="divId">Loading</div>
<input id="submit" type="button" value=" Click Me " />

JavaScript

var bigSrc = "Image Source";

var img = new Image(),
    oWidth, oHeight;

img.onload = function() {
    oWidth = this.width;
    oHeight = this.height;
    this.width = 300;
    this.height = 200;
    this.id = "bigImg";
}
img.src = bigSrc;

$("#submit").click(function(e) {
    $("#divId").append(img);
    $("#bigImg").animate({
        height: oHeight,
        width: oWidth,
    }, 500);
});​

Check this demo jsFiddle

You can tweak to suit you. Hope this helps you.

Upvotes: 3

iono
iono

Reputation: 2763

Okay, I see what you mean now.

$("#bigImg").width() will return the width in px, and height will do similar. You can also use .outerWidth() and .innerWidth() to include padding/border or just padding, respectively.

From your code, you've already changed the original dimensions of the image by using inline styles. Instead, save the image dimensions, change the image to 200 x 300px in jQuery, do what you want to it, then change it back to original dimensions:

var originalWidth = $("#bigImg").width();
var originalHeight = $("#bigImg").height();

$("#bigImg").css({
    width: '200px',
    height: '300px'
});

//Do whatever you meant to do here, the when you're finished...

$("#bigImg").animate({
    width: originalWidth,
    height: originalHeight,
},500);

jQuery documentation: http://api.jquery.com/animate/ or http://api.jquery.com/category/dimensions/

Upvotes: 1

Related Questions