jgb
jgb

Reputation: 231

jQuery toggle image swap and show hide another div

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>

Upvotes: 1

Views: 804

Answers (2)

Robert McKee
Robert McKee

Reputation: 21477

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>

Upvotes: 2

tnga
tnga

Reputation: 182

Perhaps this can help!

$('#swap-img').click(function () {
    this.src = (this.src=='i/icon.png')?'i/close.png':'i/icon.png';
});

Upvotes: 1

Related Questions