Jamal Ejaz
Jamal Ejaz

Reputation: 33

jQuery image src not changing

Can someone help me with this? I am changing image on image click. When I do it without animation it works fine but transition is jerky.

<script>
  $("#thumbs img").click(function() {
    $("#mainImage").attr('src',$(this).attr('src').replace('thumbnails','ovado').replace('png','jpg'));
  })
</script>

But when I add some animation script animation works but every time same image loads. Please see the code below and try to help me if you can.

<script>
  $("#thumbs img").click(function() {
      $("#mainImage").fadeOut(1000, function() {
          $("#mainImage").attr('src',$('#thumbs img').attr('src').replace('thumbnails','ovado').replace('png','jpg'));
      }).fadeIn(1000);
      return false;
  });
</script>

Upvotes: 1

Views: 52

Answers (1)

RMH
RMH

Reputation: 831

I can only assume there are multiple img's inside of #thumbs. You'll want to pass the element as you were doing before, into the your next function.

  • $(this) in your first snippet represented the image you were clicking
  • By referencing it inside the click the function, you are able to pass it the fadeOut function

I showed an example of what I assume is what you're trying to accomplish. You'll want to add back the replace function.

var $thumbImgs = $("#thumbs img");
var $mainImg = $("#mainImage");
$thumbImgs.click(function() {
  var $imgClicked = $(this);
  $mainImg.fadeOut(1000, function() {
    $mainImg.attr('src', $imgClicked.attr('src'));
  }).fadeIn(1000);
});
#mainImage {
  max-width: 200px;
}
#thumbs li {
  display: inline-block;
  max-width: 100px;
}
#thumbs li img {
  max-width: 100%;
  height: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="mainImage" src="https://placekitten.com/g/500/500">
<ul id="thumbs">
  <li>
    <img src="https://placekitten.com/g/200/300">
  </li>
  <li>
    <img src="https://placekitten.com/g/400/300">
  </li>
  <li>
    <img src="https://placekitten.com/g/500/300">
  </li>
</ul>

Upvotes: 3

Related Questions