jQuery Image Swapping with Fade Effect
Today we are going to cover how to properly change the source of a single image using jQuery. We will also learn how to fade the image out prior to swapping the source, and fade the image back in after the new source has been fully downloaded.
So lets setup a scenario for our script. Lets say we have a bunch of little thumbnails below a larger image. Lets also say our desired functionality here is to have any thumbnail that is clicked on show up as a larger version in the above larger image. Presuming the small thumbnail images have links wrapped around them with a href attribute pointing to the larger version of each thumbnail, we have something to work with.
To begin, we want to set up new click events for each thumbnails anchor tag and prevent the user from acutely being directed to this image file in the browser.
$('a.thumbnail').click(function(){ return false; });
So in the above code we find all anchor elements with a class of “thumbnails” and run over each instance of one. When we find an anchor element that meets this requirement we setup a new click event with an empty anonymous function. Finally in our empty function, we use the “return false;” to prevent the browser from performing the redirect to the image file.
Next we need to gather the clicked anchor tag’s “href” attribute value, and place it into a variable that we will use later on.
$('a.thumbnail').click(function(){ var src = $(this).attr('href'); return false; });
Next, lets prevent from loading images we have already clicked on by comparing our gathered src, to our already set large image’s src, like so:
$('a.thumbnail').click(function(){ var src = $(this).attr('href'); if (src != $('img#largeImg').attr('src')) { } return false; });
Basically all we are doing is is saying, “If our gathered src is NOT equal to our larger image’s already set ssrc, proceed on to changing the large image’s source”.
Great, now that we have the larger version’s source of our clicked thumbnail, we can proceed on to swapping the image with this new source:
$('a.thumbnail').click(function(){ var src = $(this).attr('href'); if (src != $('img#largeImg').attr('src')) { $('img#largeImg').stop().animate({opacity:'0'},function(){ $(this).attr('src',src); }); } return false; });
So here we are pointing the larger image who has and id of “largeImg”, and starting to animate the image’s opacity to 0. Because there is a callback when using jQuery animate, we make use of it to set the source (src=””) of our larger image to our gather thumbnail’s source. We make use of the callback in our animate to prevent the “image source swapping” from happening while the image is still visible.
Next, we want to make sure that our image has fully been downloaded prior to actually making the image indeed visible again. To do this, we make use of the jQuery .load() functionality that will listen to our large image, and perform what we need when the image is ready to be visible.
$('a.thumbnail').click(function(){
var src = $(this).attr('href');
if (src != $('img#largeImg').attr('src')) {
$('img#largeImg').stop().animate({opacity:'0'},function(){
$(this).attr('src',src);
}).load(function(){
$(this).stop().animate({opacity:'1'});
});
Erectile dysfunction super viagra online is the inability to obtain erection and perform satisfactorily during sex. It is recommended by the doctor to take this medicine without consult of doctor.Live happy with the sex power enhancing pills have strong chemical composition which usually shows bad sign on health. buy levitra professional It's considered The World'Strongest sildenafil cost Antioxidant, and it's totally natural. For instance, if you are buying Sildenafil tablets from Kamagra Tablets, then you can visit their webpage and get all answers for your questions. viagra online heritageihc.com has been really very helpful for women it has proven to be an effective medication and a big success among women facing problems of conception. }
return false;
});
So as you can see out last step in the .load() callback functionality is to animate our image back to an opacity of 1 again.
Also, note how I use a .stop() prior to any .animate() call. We make use of .stop() prior to .animate() to prevent the animation fires from collecting if the user clicks our thumbnails rapidly.
So our above code is very compact and meets all our requirements of swapping in larger versions of thumbnail sources while performing a fade effect. Drum roll please….
The Problem:
Erik Kraft helped me reproduce the IE error some people might run into with this method. Apparently because we are making use of the .load() Ajax feature of jQuery and images, IE has a hard time with caching the requests. Because IE caches the requests, any second attempt to load up an already cached image, fails.
The Solution:
Lucky for us, this is a little fix. The solution is to make all requests unique to IE, so no matter if the request is cached or not our script wont fail. We can make each request unique by appending a random number to the end of our src variable, that then gets evaluated by our .load(). Like so:
$('a.thumbnail').click(function(){ var src = $(this).attr('href'); if (src != $('img#largeImg').attr('src')) { $('img#largeImg').stop().animate({opacity:'0'},function(){ $(this).attr('src',src+'?'+Math.floor(Math.random()*(10*100))); }).load(function(){ $(this).stop().animate({opacity:'1'}); }); } return false; });
So now our images that will be requested from .load(), will be looking something like this:
img/img-three.jpg?691
My random number is between 1 and 100. This random number gives me a 100 to 1 odds that out of my 4 images, the one I click will be a unique request. I will take those odds sir!
Finally, because we have introduced unique requests into the mix, we have a broken our condition that prevents us from loading images we have already clicked. The reason this breaks is cause we are now trying to compare our large image’s source to a unique version of the same url. We can fix this issue by trimming off our unique number at the end of the images url in our condition statement. Like so:
$('a.thumbnails').each(function(){ $(this).click(function(){ var src = $(this).attr('href'); if (src != $('img#largeImg').attr('src').replace(/\?(.*)/,'')) { $('img#largeImg').stop().animate({opacity:'0'},function(){ $(this).attr('src',src+'?'+Math.floor(Math.random()*(10*100))); }).load(function(){ $(this).stop().animate({opacity:'1'}); }); } return false; }); }); And that's it. Enjoy!
Devin R. Olsen