View Full Version : jQuery - animated image swap

Oct 24th, 2008, 06:22 PM
I'm trying to animate a simple image swap but it's not quite working right. Details below, here's my code thus far:

$('#zoom_control a').click(function(){
var oImg = $('.current_page').find('img');
oImg.animate({opacity: 0}, 1000, '',function(){
var sOldSrc = oImg.attr('src');
if (sOldSrc.indexOf("_zoom.png") > 0){
sNewSrc = sOldSrc.replace("_zoom.png", ".png");
$(this).html('Zoom out');
sNewSrc = sOldSrc.replace(".png", "_zoom.png");
$(this).html('Zoom in');
oImg.attr('src', sNewSrc);
oImg.animate({opacity: 1}, 1000);
return false;

So: find the image to be swapped, and animate its opacity down to 0. When the animation finishes, use the callback function to swap the src and animate the opacity back up to 1.

Simple enough, and I was surprised not to find an existing plugin that does exactly that. If you know of one, you could probably save us both some trouble :thumbsup:

In any case, the problem with this one is that the image src swap seems to screw with the opacity. It's difficult to tell what it's doing exactly, but the image fades out ok, but then flashes back up briefly, then switches immediately to the new image.

Any ideas?

Oct 31st, 2008, 08:13 PM
Well, I sort of fixed it in the end.. by animating the opacity of the container div instead of the image itself.

Apr 14th, 2009, 05:09 PM
I came across this thread while searching for "jquery image swap".

Thought I would share with you the article I found on jquery image swap (http://jquery-howto.blogspot.com/2009/04/jquery-image-swap-or-how-to-replace.html), since I already have an account here :)