legobear154
legobear154

Reputation: 431

Javascript Animate Image Resize

I am trying to make an image animate and make it larger. I have gotten it to change size but I am now trying to make it so none of the surrounding elements don't get moved around as well. I am using jQuery to do the animations and for some reason it wont increment the margin's every step. It only does it after it has finished. I thought I read the jQuery docs correctly. Here is my code so far:

$(document).ready(function(){
    $(".image").mouseenter(function(){
        $(this).animate({height: "176px", width: "250px"},
            {
            step: function(now, fx) {
                $(this).css("margin-left","-=0.076");
                $(this).css("margin-right","-=0.084");
                $(this).css("margin-bottom","-=0.152");
            }
        });
    });
    $(".image").mouseleave(function(){
        $(this).animate({height: "100px", width: "174px"},
            {
            step: function(now, fx) {
                $(this).css("margin-left","+=0.076");
                $(this).css("margin-right","+=0.084");
                $(this).css("margin-bottom","+=0.152");
            }
        });
    });
});

Upvotes: 1

Views: 7194

Answers (2)

Connor
Connor

Reputation: 1034

Try CSS3 animations:

img{
-webkit-transform:scale(0.6); /*Webkit: Scale down image to 0.6x original size*/
-moz-transform:scale(0.6); /*Mozilla scale version*/
-o-transform:scale(0.6); /*Opera scale version*/
-webkit-transition-duration: 0.5s; /*Webkit: Animation duration*/
-moz-transition-duration: 0.5s; /*Mozilla duration version*/
-o-transition-duration: 0.5s; /*Opera duration version*/
}

.hovergallery img:hover{
-webkit-transform:scale(0.9); /*Webkit: Scale up image to most of the original size*/
-moz-transform:scale(0.9); /*Mozilla scale version*/
-o-transform:scale(0.9); /*Opera scale version*/
}

The above will scale the image on hover.

Upvotes: 2

elclanrs
elclanrs

Reputation: 94101

Without your html it's hard to tell but I think you're doing it the hard way. I suggest you do as much as possible with css and html and then worry about javascript. If you create a container with the same size as your image then you can just center the picture inside the container using the usual method to center stuff in css, but you animate it. I also would create a function to handle those animation just so its easier to use.

Check simple demo here: jsfiddle (cute kitten included)

$('img').animate({
    width: 200,
    height: 150,
    top: 0,
    marginTop: '75px', // heigth / 2
    marginLeft: '100px' // width / 2
});

Upvotes: 1

Related Questions