Image Replacement Gallery
• Tags: jQuery
For both personal and work-related projects I have, time and time again, needed a simple image replacement script. Of course when starting out we first look for examples and tutorials from books and other websites. This is when I stumbled across the ‘Image replacement gallery’ snippet from Web Designer Wall.
After implementing their code, I still felt it was lacking slightly. Therefore I decided to develop the code further to give a cleaner finish and put jQuery’s animation to good use.
I felt the code should, once a thumbnail is clicked:
- Fade out the existing enlarged image
- Change the
srcattribute of the enlarged image - Amend the
altandtitlevalues of the enlarged image (based on thealtof the thumbnail) - Remove
class="current"from all thumbnails and add to the click thumbnail - Fade in the new enlarged image
For added effect, in the demo I have including a loading graphic which is displayed when the enlarged image is faded out. This is achieved by adding a background image to the enlarged image’s div
This may seem like just another Image Replacement Gallery script, but it can act as a great building block for more complicated galleries and once that I use often on my own projects.
View the finished code below or try out the demo.
The Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | $(function() { // When a thumbnail is clicked $(".gallery .thumbnails a").click(function() { // Get enlarged image attributes var largeImg = $(".gallery .feature img"); var largeImgPath = $(this).attr("href"); var largeImgTitle = $(this).children("img").attr("alt"); var largeThumbnail = $(this); // Fade out enlarged image $(largeImg).fadeOut('slow', function() { // Change the attributes of the enlarged large image $(largeImg).attr({ src: largeImgPath, alt: largeImgTitle, title: largeImgTitle }).load(function() { // Once image is loaded: // Remove class="current" from all thumbnails and add to clicked thumbnail $(".gallery .thumbnails").children().removeClass("current"); $(largeThumbnail).addClass("current"); // Fade in enlarged image $(largeImg).fadeIn('slow'); }); }); return false; }); }); |