Reputation: 1261
I have a little animation that increases the size of my thumbnail on hover which works but affects the position of the rest of the images.
the problem is when you hover over a img the other img's move down, and right to accommodate for the space taken by the animation. I want the other images not to move as the one is animating.
$num and the for loop is pulling images from a MySQL table, ignore
<html>
<?php
for($i; $i < $num; $i++){
echo "<img class='img' id='img" . $i . "' />";
}
?>
<script>
$('.img').hover(
function(){
$(this).animate({
width: "+=14",
height: "+=14",
left: "-7",
bottom: "-7"
});
}, function(){
$(this).animate({
width: "-=14",
height: "-=14",
left: "0",
bottom: "0"
});
}
);
</script>
<css>
.img{
padding: 10px;
position: relative;
cursor: pointer;
}
</html
Upvotes: 1
Views: 49
Reputation: 711
SpaceDog's answer works quite well if you have at least enough padding to account for adjusting the padding, but in cases where there's no padding this solution might work better:
$(function( ){
$(window).ready(function( ){
$('.img').each(function( ){
$(this).css({'top': $(this).offset( ).top, 'left': $(this).offset( ).left});
});
$('.img').css({'position': 'absolute', 'z-index': 1});
});
$('.img').hover(
function(){
$(this).css('z-index', 10);
$(this).animate({
width: "+=14",
height: "+=14",
left: "-=7",
top: "+=7"
});
}, function(){
$(this).css('z-index', 1);
$(this).animate({
width: "-=14",
height: "-=14",
left: "+=7",
top: "-=7"
});
}
);
});
Here's a JSFiddle
Basically, it loops through each image and sets its top and left position based on its own position, then sets the image's position to absolute so that it won't interfere with any of the elements around it. So, it takes statically positioned images and makes them absolute without affecting where they're at. Then it animates the images almost exactly how you had originally intended.
Again, SpaceDog's answer works if you're working with enough padding.
Upvotes: 2
Reputation: 3269
You can get it to do what (I think) you want by adjusting the padding in the animation rather than the left/bottom position, like this:
$('.img').hover(
function(){
$(this).animate({
width: "+=14",
height: "+=14",
padding: "-=7"
});
}, function(){
$(this).animate({
width: "-=14",
height: "-=14",
padding: "+=7"
});
}
);
Here's a demo.
Upvotes: 0