Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Make Image Change javascript (for theme.js file)
$(document).ready(function() {
thumbnails = $('img[src*="/products/"]').not(':first');
if (thumbnails.length) {
thumbnails.bind('click', function() {
var arrImage = $(this).attr('src').split('?')[0].split('.');
var strExtention = arrImage.pop();
var strRemaining = arrImage.pop().replace(/_[a-zA-Z0-9@]+$/,'');
var strNewImage = arrImage.join('.')+"."+strRemaining+"."+strExtention;
if (typeof variantImages[strNewImage] !== 'undefined') {
productOptions.forEach(function (value, i) {
optionValue = variantImages[strNewImage]['option-'+i];
if (optionValue !== null && $('.single-option-selector:eq('+i+') option').filter(function() { return $(this).text() === optionValue }).length) {
$('.single-option-selector:eq('+i+')').val(optionValue).trigger('change');
}
});
}
});
}
});
@jonathanmoore

This comment has been minimized.

Copy link

jonathanmoore commented May 8, 2018

Currently this snippet does not work with many of the Shopify themes (free and premium). Line 12 looks to match the variant image value to the variant select element. However, in the markup of most themes there is often line breaks or whitespace between the <option></option> tags and the variant value.

The solution is to apply a simple .trim() on line 12 when trying to match the variant image text and variant option value. Here is a corrected version that should work more reliably across themes:

$(document).ready(function() {
  thumbnails = $('img[src*="/products/"]').not(':first');
  if (thumbnails.length) {
    thumbnails.bind('click', function() {
      var arrImage = $(this).attr('src').split('?')[0].split('.');
      var strExtention = arrImage.pop();
      var strRemaining = arrImage.pop().replace(/_[a-zA-Z0-9@]+$/,'');
      var strNewImage = arrImage.join('.')+"."+strRemaining+"."+strExtention;
      if (typeof variantImages[strNewImage] !== 'undefined') {
          productOptions.forEach(function (value, i) {
           optionValue = variantImages[strNewImage]['option-'+i];
           if (optionValue !== null && $('.single-option-selector:eq('+i+') option').filter(function() { return $(this).text().trim() === optionValue }).length) {
             $('.single-option-selector:eq('+i+')').val(optionValue).trigger('change');
           }
        });
      }
    });
  }
});
@designmarkt

This comment has been minimized.

Copy link

designmarkt commented May 20, 2018

Hi,

just noticed that the function is not working anymore on debut theme.
I just updated your code but its still not working. Do you have any other suggestions for me ?

https://screenshot.click/2018-05-20_15-33-34.mp4

thank you !
best regards, Sara

@pliew

This comment has been minimized.

Copy link

pliew commented May 24, 2018

Honestly. All of this can be simplified as most of the code is working backwards to figure out which select should be used and what values should be set. Only 3 options are available so code can be super simple.

I simplified this by doing the following:

  1. Added this script to the top of product-template.liquid:
<script>
  var product_variant_map = {};
  {% for variant in product.variants %}
    product_variant_map["{{variant.id}}"] = {{ variant | json }};
  {% endfor %}
</script>

  1. Add data-variant-id to the img. This will require shifting from looping through product.variants rather than product.images. This should be acceptable as we only want to show variant images.

  2. Add the following js:

$(document).ready(function() {
  thumbnails = $('img[src*="/products/"]');
  if (thumbnails.length) {
    thumbnails.bind('click', function(event) {
      var item = $(event.currentTarget);
      // Update the alternate selector
      var v = product_variant_map[item.data('variant-id')];
      if ( v.option1 !== null ) { $('.single-option-selector:eq(0)').val(v.option1).trigger('change'); }
      if ( v.option2 !== null ) { $('.single-option-selector:eq(1)').val(v.option2).trigger('change'); }
      if ( v.option3 !== null ) { $('.single-option-selector:eq(2)').val(v.option3).trigger('change'); }
    });
  }
});

Phil
Byward Labs

@JessKire

This comment has been minimized.

Copy link

JessKire commented Jun 16, 2018

I need help! The function also just stopped working for me all of a sudden. No idea why. Now when I click on the photo it will just open in a seperate browser. Did you find a solution Sara?

@pliew

This comment has been minimized.

Copy link

pliew commented Jul 4, 2018

@JessKire
Sara's issue was regarding the proper variants loading in the shopping cart. If a new window is popping up then that is an unrelated issue. If you are getting a new window then check the product template code to see if a target window is being specified

@PhilledUP

This comment has been minimized.

Copy link

PhilledUP commented Jul 5, 2018

@pliew I've got the repo's method working, but am interested in your solution. On step 2, what do you mean add data-variant-id to the img? Are you saying the variant image should have id="data-variant-id"?

@marcomagdy9

This comment has been minimized.

Copy link

marcomagdy9 commented Jul 6, 2018

hi , I am a newbie at coding ,I came from this guide https://help.shopify.com/en/themes/customization/products/variants/select-variants-by-clicking-images?utm_source=gurucopy&utm_medium=link&utm_campaign=Gurus
the main problem is that clicking on variant image does not choose the variant itself and the image just appears with the last variant chosen manually ... although it may work well sometimes for no reason !
When I followed the guide for solving the problem ,nothing changed !

code2

I am using shopify theme called shoptimized .in coding ,there is no file named theme.js or theme.js.liquid . And so,I created theme.js file in assets section ,and copied the code in it ,I tried the code in this post and in jonathanmoore comment .nothing new happened !
code1

a link to my store product to check how the variant and images work : https://stressreliefworld.com/collections/best-selling-stress-relievers/products/cute-anti-stress-animal-toy-squeeze-cat-and-panda-for-stress-relief?variant=14290380456054

thank you guys for reading ! waiting for answers :)



NEW UPDATE : (( the function works well in a certain case only ))
I have two types of variants :shape and color
hint: the function meant here is choosing the variant from its image.

the function works when >> I choose shape A with the white color variant ... then choose an image of shape B with WHITE color which has THE SAME COLOR OF THE LAST CHOSEN VARIANT ..
-after that,if I choose shape C with white color also >> the function still works ....
-but if I choose Shape D next with ANOTHER COLOR (black color for example) >> THE VARIANT WON'T BE CHOSEN and here comes the bug/error.
-Another hint: if the next image chosen after (shape D black color) was of the same last shape (shape D) but with another color (Color Red) >> the function works and the variant is chosen automatically

@spareek90

This comment has been minimized.

Copy link

spareek90 commented Oct 15, 2018

Currently this snippet does not work with many of the Shopify themes (free and premium). Line 12 looks to match the variant image value to the variant select element. However, in the markup of most themes there is often line breaks or whitespace between the <option></option> tags and the variant value.

The solution is to apply a simple .trim() on line 12 when trying to match the variant image text and variant option value. Here is a corrected version that should work more reliably across themes:

$(document).ready(function() {
  thumbnails = $('img[src*="/products/"]').not(':first');
  if (thumbnails.length) {
    thumbnails.bind('click', function() {
      var arrImage = $(this).attr('src').split('?')[0].split('.');
      var strExtention = arrImage.pop();
      var strRemaining = arrImage.pop().replace(/_[a-zA-Z0-9@]+$/,'');
      var strNewImage = arrImage.join('.')+"."+strRemaining+"."+strExtention;
      if (typeof variantImages[strNewImage] !== 'undefined') {
          productOptions.forEach(function (value, i) {
           optionValue = variantImages[strNewImage]['option-'+i];
           if (optionValue !== null && $('.single-option-selector:eq('+i+') option').filter(function() { return $(this).text().trim() === optionValue }).length) {
             $('.single-option-selector:eq('+i+')').val(optionValue).trigger('change');
           }
        });
      }
    });
  }
});

@jonathanmoore I tried this code and though it works well, I have a slight issue that I can't figure out. The dropdown changes for all images when selected, except for the first one. I feel that this is an index issue. Any help is appreciate! Also, I'm using the Pop theme.

@spareek90

This comment has been minimized.

Copy link

spareek90 commented Oct 16, 2018

I was able to figure out the issue. For anyone else looking please use the following code as the current version won't work for the first element.

$(document).ready(function() {
  thumbnails = $('img[src*="/products/"]');
  if (thumbnails.length > 1) {
    thumbnails.bind('click', function() {
      var arrImage = $(this).attr('src').split('?')[0].split('.');
      var strExtention = arrImage.pop();
      var strRemaining = arrImage.pop().replace(/_[a-zA-Z0-9@]+$/,'');
      var strNewImage = arrImage.join('.')+"."+strRemaining+"."+strExtention;
      if (typeof variantImages[strNewImage] !== 'undefined') {
          productOptions.forEach(function (value, i) {
           optionValue = variantImages[strNewImage]['option-'+i];
           if (optionValue !== null && $('.single-option-selector:eq('+i+') option').filter(function() { return $(this).text().trim() === optionValue }).length) {
             $('.single-option-selector:eq('+i+')').val(optionValue).trigger('change');
           }
        });
      }
    });
  }
});
@pliew

This comment has been minimized.

Copy link

pliew commented Dec 13, 2018

@pliew I've got the repo's method working, but am interested in your solution. On step 2, what do you mean add data-variant-id to the img? Are you saying the variant image should have id="data-variant-id"?

@PhilledUP Yes. that's exactly what I meant. Alot of this code is working backwards to figure out what select to change. By setting the variant-id as a data attribute and then having the variant option values available then you just change the options accordingly and no need to run through each select option.

@joan1990

This comment has been minimized.

Copy link

joan1990 commented Dec 30, 2018

I was able to figure out the issue. For anyone else looking please use the following code as the current version won't work for the first element.

$(document).ready(function() {
  thumbnails = $('img[src*="/products/"]');
  if (thumbnails.length > 1) {
    thumbnails.bind('click', function() {
      var arrImage = $(this).attr('src').split('?')[0].split('.');
      var strExtention = arrImage.pop();
      var strRemaining = arrImage.pop().replace(/_[a-zA-Z0-9@]+$/,'');
      var strNewImage = arrImage.join('.')+"."+strRemaining+"."+strExtention;
      if (typeof variantImages[strNewImage] !== 'undefined') {
          productOptions.forEach(function (value, i) {
           optionValue = variantImages[strNewImage]['option-'+i];
           if (optionValue !== null && $('.single-option-selector:eq('+i+') option').filter(function() { return $(this).text().trim() === optionValue }).length) {
             $('.single-option-selector:eq('+i+')').val(optionValue).trigger('change');
           }
        });
      }
    });
  }
});

YEAAH IT WORKS AT DEBUT THEME , THANKS

@nehagoyal2786

This comment has been minimized.

Copy link

nehagoyal2786 commented Jan 18, 2019

I am using Prestige theme. I tried this code, but did not work. I want when image is clicked, variant value must change.
Someone please help, here is the link:

https://www.statementoutfit.com/products/steampunk-trendy-zonnebril-design-modern-double-dubbel-hip-en-eye-catching-statement?variant=18146438971489

@nehagoyal2786

This comment has been minimized.

Copy link

nehagoyal2786 commented Jan 19, 2019

Someone please help.

@koky462

This comment has been minimized.

Copy link

koky462 commented Mar 9, 2019

hi , I am a newbie at coding ,I came from this guide https://help.shopify.com/en/themes/customization/products/variants/select-variants-by-clicking-images?utm_source=gurucopy&utm_medium=link&utm_campaign=Gurus
the main problem is that clicking on variant image does not choose the variant itself and the image just appears with the last variant chosen manually ... although it may work well sometimes for no reason !
When I followed the guide for solving the problem ,nothing changed !

code2

I am using shopify theme called shoptimized .in coding ,there is no file named theme.js or theme.js.liquid . And so,I created theme.js file in assets section ,and copied the code in it ,I tried the code in this post and in jonathanmoore comment .nothing new happened !
code1

a link to my store product to check how the variant and images work : https://stressreliefworld.com/collections/best-selling-stress-relievers/products/cute-anti-stress-animal-toy-squeeze-cat-and-panda-for-stress-relief?variant=14290380456054

thank you guys for reading ! waiting for answers :)

NEW UPDATE : (( the function works well in a certain case only ))
I have two types of variants :shape and color
hint: the function meant here is choosing the variant from its image.

the function works when >> I choose shape A with the white color variant ... then choose an image of shape B with WHITE color which has THE SAME COLOR OF THE LAST CHOSEN VARIANT ..
-after that,if I choose shape C with white color also >> the function still works ....
-but if I choose Shape D next with ANOTHER COLOR (black color for example) >> THE VARIANT WON'T BE CHOSEN and here comes the bug/error.
-Another hint: if the next image chosen after (shape D black color) was of the same last shape (shape D) but with another color (Color Red) >> the function works and the variant is chosen automatically

Hey @marcomagdy9 I am also using Shoptimized theme. I just read through this tread and implemented on my store.

I went to search and I have timber.js.liquid. So I pasted the code at the bottom of the page and it worked perfectly for me!
image

@elihaun

This comment has been minimized.

Copy link

elihaun commented Mar 11, 2019

I have a question: How can you get this to work for mobile? We use the Retina theme (from OutOfTheSandbox), and this works just fine on desktop, but on mobile it refuses to work. My boss is adamant that it needs to work on BOTH desktop and mobile, but I can't seem to get it working on mobile. Any suggestions?

@nsbabrah

This comment has been minimized.

Copy link

nsbabrah commented Apr 17, 2019

Hi my some products worked and change variant on clicking thumbnail image but some still doesn't change variant when I click on images and they also give me jquery error maximum stack exceed. when I go to shopify -> products and check they all are same and each variants have theirs own images.

@nsbabrah

This comment has been minimized.

Copy link

nsbabrah commented Apr 17, 2019

I just figure out that some product images upload by url would not work you have to upload images manually when adding new product some time we use csv and add image url make sure we add images manually in shopify if we want this feature to work.

@nsbabrah

This comment has been minimized.

Copy link

nsbabrah commented May 15, 2019

Hi I have this issue everything working fine but I can not solve this error anybody know what's the issue Maximum call stack size exceeded in jquery

@clemire

This comment has been minimized.

Copy link

clemire commented Jul 16, 2019

I have a question: How can you get this to work for mobile? We use the Retina theme (from OutOfTheSandbox), and this works just fine on desktop, but on mobile it refuses to work. My boss is adamant that it needs to work on BOTH desktop and mobile, but I can't seem to get it working on mobile. Any suggestions?

I'm having the same issue with the Parallax theme from OutOfTheSandbox. Works fine on desktop, breaks on mobile. Any fixes available?

@teexpression

This comment has been minimized.

Copy link

teexpression commented Jul 24, 2019

Hi, This works perfectly for the product page. But in my quick view (quick shop) pop up, this doesn't work. I would appreciate a ton if someone genius can solve the issue. Please.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.