Reputation: 419
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!
Upvotes: 1
Views: 94
Reputation: 2333
You could do the following with jQuery. More info can be found here:
<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.
Upvotes: 0
Reputation: 50643
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);
}
});
Upvotes: 0
Reputation: 255085
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);
Upvotes: 2
Reputation: 5356
$('#Id').click(function(){
$('.image1').attr('src','2.jpg');
$('.image2').attr('src','1.jpg');
});
Upvotes: 0