I have a list of images (thumbs) near a container with one image. I want jQuery to count the index of the <a> element, and then replace the number of the src attribute of the image below.
I mean, considering this code:
<ul class="thumbs">
<li><a href="#"><img src="img1.jpg" alt="image here"/></a></li>
<li><a href="#"><img src="img2.jpg" alt="image here"/></a></li>
<li><a href="#"><img src="img3.jpg" alt="image here"/></a></li>
<li><a href="#"><img src="img4.jpg" alt="image here"/></a></li>
</ul>
<div class="container">
<img src="img1.jpg" alt="destiny image here"/>
</div>
The expected behavior is, when user clicks the second <a>, the .container img change its src attribute to img1.jpg. And when click the fourth <a> the attribute should change to img3.jpg.
I have got this far: jsFiddle demo
$(document).ready(function() {
$(".thumbs li a").click(function () {
//$('div.container').toggleClass('on');
var index = $(".thumbs li a").index(this);
$("div.container img[src^='img']").replaceWith("img" + index + ".jpg");
});
});
It doesn't does absolutely nothing. I don't think to understand properly the .replaceWith method.
Also, the commented line works fine when it's alone... when the rest of code is present div.container don't change its class. Is this related to the way I declare the variable?
"div.container img[src^="img"]"is a syntax error. Watch your quotes. Also,replaceWith()does not do what you think it does.