1

I'm trying to toggle an image and another div at the same time. I have it so that when you click on the image, the image switches and shows another div, but when you click again the image doesn't switch back. What am I missing to make it so that it switches back?

$("#swap").click(function() {
  $("#swap-nav").toggle("slow", function() {});
});


$('#swap-img').click(function() {
  this.src = 'i/icon.png';
}, function() {
  this.src = 'i/close.png';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="swap">
  <img id="swap-img" src="i/icon.png" data-swap="i/close.png">
</li>
<div id="swap-nav">
  <li>one</li>
  <li>two</li>
</div>
Robert McKee
  • 21,305
  • 1
  • 43
  • 57
jgb
  • 231
  • 3
  • 13
  • 2
    possible duplicate of [jQuery click / toggle between two functions](http://stackoverflow.com/questions/4911577/jquery-click-toggle-between-two-functions) – lmgonzalves Sep 18 '15 at 18:01

2 Answers2

2

I would combine the two into a single event, like so:

$("#swap").click(function() {
  $("#swap-nav").toggle("slow", function() {});
  var img = $('img[data-swap]',this);
  var temp = img[0].src;
  img[0].src = img.data('swap');
  img.data('swap',temp);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="swap">
  <img src="http://placehold.it/25x25" data-swap="http://placehold.it/25x25/00ff00">
</li>
<div id="swap-nav">
  <li>one</li>
  <li>two</li>
</div>
Robert McKee
  • 21,305
  • 1
  • 43
  • 57
  • Updated answer to pick the img with the data-swap attribute, just in case there are other images in your final solution. – Robert McKee Sep 18 '15 at 18:13
1

Perhaps this can help!

$('#swap-img').click(function () {
    this.src = (this.src=='i/icon.png')?'i/close.png':'i/icon.png';
});
tnga
  • 182
  • 2
  • 8
  • This would break if the browser returns a value other than the one you put in it (which some do!). For example, feeding it `i/icon.png` may return a full url, like `http://mysite/i/icon.png`. – Robert McKee Sep 18 '15 at 18:07