1

I have to images and I'd like to switch the src attributes of the images, when one is clicked:

Before:

<img src="1.jpg" class="image1" />
<img src="2.jpg" class="image2" />

After clicking on image 1 or 2:

<img src="2.jpg" class="image1" />
<img src="1.jpg" class="image2" />

I can change the src of the clicked image, but I don't seem to be able to store the original src-attribute in any way to pass it to the other image.

Thanks!

2
  • I wonder what the use case is for this sort of thing. Commented Oct 2, 2012 at 10:14
  • Of course this is just an excerpt. It's an image-gallery. The first image is shown big, when you click on a thumbnail, the thumbnail is shown instead of the big image. So what to do to see the first pic again? I need to store the src for the big image somewhere (by exchanging the two images). Commented Oct 2, 2012 at 10:48

4 Answers 4

2

You won't believe but you can store it in a 3rd variable!!

var img1 = $('.image1'),
    img2 = $('.image2');

var originalSrc = img1.attr('src');

img1.attr('src', img2.attr('src'));
img2.attr('src', originalSrc);
Sign up to request clarification or add additional context in comments.

3 Comments

That's what I tried, my code: $('.image1').click(function() { orgSource = $(this).attr("src); alert(orgSource); $(this).parents(".node").find(".image2").attr("src", orgSource); ...gives me TWO alerts, one with the first and one with the second src...
@user1632757: reproduce that on jsfiddle.net
Thanks for this answer! I know this is pretty basic but it was a bit of a revelation!
0
$('#Id').click(function(){
$('.image1').attr('src','2.jpg');
$('.image2').attr('src','1.jpg');
});

Comments

0

You can do it the following way:

$('.image1 , .image2').click(function() {
   if ($(this).prev().length) {
      temp = $(this).attr('src');
      $(this).attr('src', $(this).prev().attr('src') );
      $(this).prev().attr('src',temp);
   } else {
      temp = $(this).attr('src');
      $(this).attr('src', $(this).next().attr('src') );
      $(this).next().attr('src',temp);
   }
});

Comments

0

You could do the following with jQuery. More info can be found here:

http://jquery.com

<script type="text/javascript" src="jquery-1.8.0">
$(function(){
  $("img").click(function(){
   $(this).closest("img").attr("src",$(this).attr("src"));
  });
});
</script>

Hope this helps you out.

Comments

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.