2

I have an image I would like to load at 200px by 200px briefly, and then smoothly scale to 50px on page load. I have done it with a show / hide technique, showing larger > then hide > showing smaller with fades; but I need the transition.

Thus far. But Turning out pretty ugly -

var bigSrc = "averycoolimage.jpg";

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

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

$(function() {
    $("#divId").append(img);

    $("#bigImg").animate({
        height: oHeight,
        width: oWidth,
    }, 500);
});
Dr Upvote
  • 8,023
  • 24
  • 91
  • 204

2 Answers2

4

Slightly different take on the problem using CSS3 transitions instead of CSS3 or JS animations.

HTML

<img src="http://img1.wikia.nocookie.net/__cb20120923041524/kongregate/images/0/03/Awesome_face.png" />

CSS

img {
    -webkit-transition:all .5s;
    transition:all .5s;
    width:200px;
    height:200px;
}
img.small {
    height:50px;
    width:100px;
}

Javascript

$( document ).ready(function() {
    $('img').addClass('small');
});

Fiddle Example

Matthew Darnell
  • 4,538
  • 2
  • 19
  • 29
3

You can also do this with CSS3 animations (and therefore without JavaScript):

img {
     width: 50px;
    -moz-animation: scale 0.5s; /* Firefox */
    -webkit-animation: scale 0.5s; /* Safari and Chrome */
    -o-animation: scale 0.5s; /* Opera */
    animation: scale 0.5s;
}
@keyframes scale {
    from {
        width:200px;
    }
    to {
        width:50px;
    }
}
@-moz-keyframes scale { /* Firefox */
    from {
        width:200px;
    }
    to {
        width:50px;
    }
}
@-webkit-keyframes scale { /* Safari and Chrome */
    from {
        width:200px;
    }
    to {
        width:50px;
    }
}
@-o-keyframes scale { /* Opera */
    from {
        width:200px;
    }
    to {
        width:50px;
    }
}

JSFiddle here: http://jsfiddle.net/a4Cm7/1/