Skip to content
Advertisement

Change image when another image is clicked

I am trying to change the big image when another small image is clicked, kind of like a product display on an e-commerce website. But my code doesn’t seem to work.

jQuery(document).ready(function($) {
  $('.blue-button').on({
    'click': function() {
      $('#change-image').attr('src', 'https://cdn.shopify.com/s/files/1/0781/4423/files/02_8df18841-8d84-4a96-9611-e5a965dce73c.jpg?v=1568864598');
    }
  });

  $('.yellow-button').on({
    'click': function() {
      $('#change-image').attr('src', 'https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/mothers-day-flower-bouquet-1588610191.jpg');
    }
  });
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="button-container">
  <img src="https://i.pinimg.com/originals/12/e2/6d/12e26d72c68442640b27583cff8d50e7.png" class="blue-button box">
  <img src="https://i.pinimg.com/originals/16/cd/d9/16cdd95fab4a41e8cbe3e1f724343f49.png" class="yellow-button box">
</div>

<img id="change-image" src="https://img.freepik.com/free-vector/beautiful-watercolour-bouquet-flowers_52683-45189.jpg?size=626&ext=jpg" />

Advertisement

Answer

Don’t repeat JavsScript code. Instead delegate a click to every .button-container‘s img element:

jQuery(function($) {
  const $image = $("#change-image");
  $(".button-container").on("click", "img", function() {
    $image.attr("src", this.src);
  });
});
.button-container img {max-height: 60px;}
<div class="button-container">
 <img src="https://i.pinimg.com/originals/12/e2/6d/12e26d72c68442640b27583cff8d50e7.png" class="blue-button box">
 <img src="https://i.pinimg.com/originals/16/cd/d9/16cdd95fab4a41e8cbe3e1f724343f49.png" class="yellow-button box">
</div>

<img id="change-image" src="https://img.freepik.com/free-vector/beautiful-watercolour-bouquet-flowers_52683-45189.jpg?size=626&ext=jpg"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Another suggestion is not to load the fullsize images if you need thumbnails.
Store the Full-size image inside the data-* attribute of the thumbnail image:

jQuery(function($) {
  const $image = $("#change-image");
  $(".button-container").on("click", "img", function() {
    $image.attr("src", this.dataset.src);
  });
});
.button-container img {max-height: 60px;}
<div class="button-container">
 <img src="https://placehold.it/50x50/0bf" data-src="https://placehold.it/250x150/0bf">
 <img src="https://placehold.it/50x50/f0b" data-src="https://placehold.it/250x150/f0b">
</div>

<img id="change-image" src="https://placehold.it/250x150/0bf"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement