Use Jquery to do an image swapover | South Coast Web Design Ltd
South Coast Web Design Ltd
Use Jquery to do an image swapover Feb 16

Slideshow_icon
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..

<script src="/js/jquery.js" type="text/javascript"></script><script src="/js/javascript.js" type="text/javascript"></script>

Basic html code (without styling):

<img id="mainpic" src="images/image1.jpg" alt="Image" />

<img class="thumbnail" src="images/image1.jpg" alt="Image1" />
<img class="thumbnail" src="images/image2.jpg" alt="Image2" />
<img class="thumbnail" src="images/image3.jpg" alt="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..

Leave a Response


Top