1

I'm having some trouble figuring out how to properly update the main product image from a set of images that are available.

Within the product detail page, I have a large default image that is shown with a set of thumbnails below from lopping through all available images associated with the product.

I'm able to loop through and display all available images for the given product using.

<div class="product__photos">
{% set relatedAssets = product.productPhoto.all() %}

  {% if relatedAssets|length %}
    {% for rel in relatedAssets %}
      <div class="product__photo">
        <img src="{{ rel.getUrl('square_md') }}" alt="">
      </div>
    {% endfor %}
  {% endif %} 
</div>

What I'd like to do it update the large image once a thumbnail of the image set is clicked. I haven't been able to find anything related to successfully doing this which seems like a common pattern for an ecommerce site.

Any advice would be much appreciated!

1

Something like this (untested):

{% set relatedAssets = product.productPhoto.all() %}
{% if relatedAssets|length %}

<img id="primaryImg" src="{{relatedAssets|first.getUrl() }}">

<div class="product__photos">

    {% for rel in relatedAssets %}
      <div class="product__photo">
        <a href="#" class="thumbImg" data-lrgimg="{{ rel.getUrl() }}"><img src="{{ rel.getUrl('square_md') }}" alt=""></a>
      </div>
    {% endfor %}

</div>
{% endif %} 

</div>

<script>
$( document ).ready(function() {
  $(".thumbImg").click(function(){
    $("#primaryImg").attr({ "src": $(this).data('lrgimg') });
  });
});
</script>
| improve this answer | |
  • Thank you so much, Luke – worked like a charm! – kamicrafted Oct 31 '19 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.