To contact Ben MacGowan, please fill in the below form. Note that required fields are marked with a blue left border.

Close

Please fill in all required fields before submitting

Image Replacement Gallery

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 src attribute of the enlarged image

- Amend the alt and title values of the enlarged image (based on the alt of 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:

$(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;
	});
});