Use Jquery to do an image swapover

Hi in todays tutorial i will show a quick bit of code that will swap a thumbnail to the large image with a nice fade effect.

Firstly i am going to have to create a Large image with a unique id (#mainpic) and underneath that a couple of smaller
thumbnails which on mouseover swap to the larger image…
I am hoping you all know how to add the jquery library and a external javascript file to your page..

Basic html code (without styling):

Image

Image1
Image2
Image3

And a few basic styles :

#mainpic {
  max-width:400px;
  max-height:250px;
  border:1px solid #000;
}
.thumbnail {
  max-width:100px;
  max-height:100px;
  border:1px solid #000;
}

And now a bit of jquery magic…
The aim is to when you move the mouse over the thumbnail it will fade the mainpic out and replace it with the thumbnail you are currently hovering over.

$(document).ready(function() {
	$(".thumbnail").mouseover(function(){
		var smallthumb = $(this).attr("src");
		$("#mainpic").fadeOut(function(){
		     $('#mainpic').attr("src",smallthumb).fadeIn();
		});
	});
});

I will explain the code,
the first line means that once the document is ready the function is ready to work.
the next line catches any mouseover of anything with a class of thumbnail.. in this example our thumbnail images.
we now get the value of the item contained within the mouseover and set this to the smallthumb variable.
Now we set the item with id #mainpic to fadeOut.
We apply a function within the fadeOut to set the #mainpic value to smallthumb.
Once the fadeout effect has completed we must fadein the new mainpic.

And at first this was great.. It did exactly what i wanted it to…
however if i went over the thumbnail of the mainpic it would fadeOut and backin again.
Not very professional!

So i added a couple of lines within the function.
Firstly to get the mainpic value..
If the mainpic is the same as the thumbnail value it would not do anything..

Here is the completed jquery code and it works perfect..

$(document).ready(function() {
	$(".thumbnail").mouseover(function(){
		var smallthumb = $(this).attr("src");
		var bigthumb = $('#mainpic').attr("src");
		if(bigthumb != smallthumb){
			$("#mainpic").fadeOut(function(){
				$('#mainpic').attr("src",smallthumb).fadeIn();
			});
		}
	});
});

I hope this will help..

Copyright 2007 - 2024 southcoastweb is a brand of DSM Design.