Alex Rivera | Logout

Is there a way to grow/shrink an image on hover using Jquery?

Asked 2009-05-19T15:26:20.877
10

Is there a way, using Jquery to grow and then shrink an image (with animation so it looks smooth) on hovering without affecting the layout too much (I'm assuming the padding would have to shrink and then grow as well).


With a bit of messing around, I finally came up with the solution, thanks to everyone who helped out.

<html>
<head>
<style type="text/css"> 
    .growImage {position:relative;width:80%;left:15px;top:15px}
    .growDiv { left: 100px; top: 100px;width:150px;height:150px;position:relative }
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

</head>
<body> 
<div class="growDiv"> 
      <img class="growImage" src="image.jpg" alt="my image"> 
</div>

<script type="text/javascript">

$(document).ready(function(){

    $('.growImage').mouseover(function(){
      //moving the div left a bit is completely optional
      //but should have the effect of growing the image from the middle.
      $(this).stop().animate({"width": "100%","left":"0px","top":"0px"}, 400,'swing');
    }).mouseout(function(){ 
      $(this).stop().animate({"width": "80%","left":"15px","top":"15px"}, 200,'swing');
    });;
});
</script>
</body></html>
Edit
Report

2 Answers

17

If you have your image positioned absolutely to the document in CSS, the rest of the page layout should not change when you animate your image.

You should be able to use jQuery's animate() function. The code would look something like this:

$("#yourImage").hover(
    function(){$(this).animate({width: "400px", height:"400px"}, 1000);},        
    function(){$(this).animate({width: "200px", height:"200px"}, 1000);}
);

This example would grow the image with id=yourImage to 400px wide and tall when moused over, and bring it back to 200px wide and tall when the hover ends. That said, your issue lies more in HTML/CSS than it does jQuery.

answered 2009-05-19T15:49:50.423
3

Wanted to post a simple solution I'm using based on this post and information from Fox's answer to a related question.

Using an <img> like this: <img style="position: absolute;" class="resize" />

You can do something similar to what's below. It will take the image's current width+height, make it 3 times bigger on hover (current * 3) and then bring it back on mouse out.

var current_h = null;
var current_w = null;

$('.resize').hover(
    function(){
        current_h = $(this, 'img')[0].height;
        current_w = $(this, 'img')[0].width;
        $(this).animate({width: (current_w * 3), height: (current_h * 3)}, 300);
    },
    function(){
        $(this).animate({width: current_w + 'px', height: current_h + 'px'}, 300);
    }
);

The current_X variables are global so they will be accessible in the mouse-out action.

answered 2011-07-08T04:24:24.523

Your Answer