Reputation: 199
I'm trying to create a simple thumbnail viewer with jQuery. Here goes the code:
$(function(){
$("ul.thumbnails li").click(function(e){
var imgAlt = $(this).find('img').attr("alt"); //Get Alt Tag of Image
var imgTitle = $(this).find('a').attr("href"); //Get Main Image URL
$("img.featured").attr({ src: imgTitle , alt: imgAlt}); //Switch the main image (URL + alt tag)
});
<div class="image-gallery">
<img class="featured" src="big.jpg">
<ul class="thumbnails">
<li id="thumb01">
<a href="big.jpg"><img src="small.jpg"></a>
</li>
<li id="thumb02">
<a href="big.jpg"><img src="small.jpg"></a>
</li>
<li id="thumb03">
<a href="big.jpg"><img src="small.jpg"></a>
</li>
</ul>
.thumbnails li {
margin: 0;
padding: 5px 5px 0 5px;
list-style: none;
float: left;
overflow: hidden;
}
thumbnails li img {
width: 50px;
height: 50px;
margin: 0;
padding: 0;
float: left;
}
If i click the thumbnail, the browser goes straight to the full image instead of just changing the img src with jQuery. But I if i click somewhere inside the <li>
it works.
I know this must be simple, but I don't know where I'm going wrong. I've tried studying other galleries, like http://www.sohtanaka.com/web-design/examples/image-rotator/ , but couldn't find what I'm missing.
I could really use some help from you guys :)
Upvotes: 0
Views: 563
Reputation: 564
After setting the new source ensure that the click function return false;
in order to prevent the default browser behaviour.
Upvotes: 1
Reputation: 26514
This happens because you need to stop the browser from going to the image when clicking on the links. You can do this by using preventDefault functions which stops the current event action. In this case "click".
$(function(){
$("ul.thumbnails li").click(function(e){
var imgAlt = $(this).find('img').attr("alt"); //Get Alt Tag of Image
var imgTitle = $(this).find('a').attr("href"); //Get Main Image URL
$("img.featured").attr({ src: imgTitle , alt: imgAlt}); //Switch the main image (URL + alt tag)
e.preventDefault(); //Stop browser default behaviour
});
Upvotes: 2