0

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 Answers 3

2

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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;
});

Comments

-1

your js code is incorrect. try

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

2 Comments

ha, another race condition ;-). if this solution caters for your needs, accept Jamiec's conceptually identical answer which was submitted a few moments before mine.
Thanks very much. That work with slight addition of 'img' in front of .thumbnail $('.thumbnail img').click(function () { $(".imageforthumbs").attr('src', $(this).attr('src')); });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.