fightstarr20
fightstarr20

Reputation: 12598

jQuery swap image on button click

I am trying to create a block of three divs that when clicked will swap an image. I have this so far..

	$( ".button1" ).click(function() {
		$(this).attr("src","https://dummyimage.com/100x100/000000/fff&text=1-on")
	});
	$( ".button2" ).click(function() {
		$(this).attr("src","https://dummyimage.com/100x100/000000/fff&text=2-on")
	});
	$( ".button3" ).click(function() {
		$(this).attr("src","https://dummyimage.com/100x100/000000/fff&text=3-on")
	});
	
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button1">
    <img src="https://dummyimage.com/100x100/000000/fff&text=1-off">
</div>
<div class="button2">
    <img src="https://dummyimage.com/100x100/000000/fff&text=2-off">
</div>
<div class="button3">
    <img src="https://dummyimage.com/100x100/000000/fff&text=3-off">
</div>

This isn't working for me, does anybody have an similar example they can point me at?

I am also wanting only one 'on' image to be displayed at a time so the others will switch to off when one is on.

Upvotes: 1

Views: 851

Answers (3)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

Give all the divs the same class, then create a single click event, which will toggle the current img on, while turning the others off:

$('.button img').click(function() {
  var src = $(this).attr('src');

  $(this).attr('src', src.replace('-off', '-on'));   //change off to on

  $('img').not(this).attr('src', function(_, src) {  //change on to off
    return src.replace('-on', '-off');
  });
});

Snippet:

$('.button img').click(function() {
  var src = $(this).attr('src');
  
  $(this).attr('src', src.replace('-off', '-on'));   //change off to on
  
  $('img').not(this).attr('src', function(_, src) {  //change on to off
    return src.replace('-on', '-off');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">
  <img src="https://dummyimage.com/100x100/000000/fff&text=1-off">
</div>
<div class="button">
  <img src="https://dummyimage.com/100x100/000000/fff&text=2-off">
</div>
<div class="button">
  <img src="https://dummyimage.com/100x100/000000/fff&text=3-off">
</div>

Upvotes: 2

StackSlave
StackSlave

Reputation: 10627

$(this).attr(

should be

$(this).find('img').attr(

Upvotes: 0

Ziv Weissman
Ziv Weissman

Reputation: 4526

You are targeting the parent instead of the img.

Try .class img

for example:

$( ".button1 img" ).click(function() {
    $(this).attr("src","https://dummyimage.com/100x100/000000/fff&text=1-on")
});

This will select the image and not the parent div.

Upvotes: 0

Related Questions