user381800
user381800

Reputation:

jQuery swap image based on dropdown selection issue

So I am writing a script where when you change the dropdown selection it will change the image source.

I have everything working however the issue I am having is somehow when swapping, the original image shows/flashes and then the new image shows. What I wanted was a smooth fade out and fade in...I thought my script does just that but somehow it isn't working. Can you spot the reason?

image.fadeTo('fast',0, function() {
     image.attr("src", newImageSource).fadeTo('fast',1);
});

Again this works but it flashes the original image first before showing the swapped one. I even tried putting a delay but it didn't help.

Upvotes: 0

Views: 379

Answers (1)

idrumgood
idrumgood

Reputation: 4934

image.fadeTo('fast',0, function() {
     var tempImg = $('<img src="' + newImageSource + '">');
     $(tempImg).load(function(){
         image.attr("src", newImageSource).fadeTo('fast',1);
     });
});

I create a temporary image with the new image source, then once it's loaded (keep in mind it's not in the DOM, the user will never see it) the other image is faded back in. This asures that the new image has been loaded before attempting to fade it in, which is probably what was causing your stuttering.

Upvotes: 1

Related Questions