0
votes

I am trying to add an image src into an image in div on click of a thumbnail. The problem is that the image src do not change when another thumnail is clicked.

HTML Code is:

  <a class="thumbnail" href="#" >
     <img  src="img1">
     <img  src="img2">
     <img  src="img3">
  </a>



 <div  class="imageforthumb">
    <img class="imageforthumbs">
 </div>

Javascript im using is:

$('.thumbnail').click(function () {
var images = $('.thumbnail img').attr('src');
$(".imageforthumbs").attr('src', images)
});

once i click the first image img1, it is set to img1 and do not change to img2 when i click the thumbnail. Please advice what could be wrong here ?

3

3 Answers

2
votes

With this line:

var images = $('.thumbnail img').attr('src');

You're always getting the first image's src.

Change your code to:

$('.thumbnail img').click(function () {
    var images = $(this).attr('src');
    $(".imageforthumbs").attr('src', images)
});

Live example: http://jsfiddle.net/8hTrr/


Edit: As pointed out, you dont need jQuery to get the attr, you just need:

$('.thumbnail img').click(function () {
     $(".imageforthumbs").attr('src', this.src)
});

Updated example: http://jsfiddle.net/8hTrr/1/

0
votes

Delegate the event to each image within the <a></a> tag. Then bind the src of the clicked <img />.

$('.thumbnail').on('click', 'img', function () {
    $(".imageforthumbs")[0].src = this.src;
});
-1
votes

your js code is incorrect. try

$('.thumbnail').click(function (eve) {
    $(".imageforthumbs").attr('src', $(eve.target).attr('src'));
});