Skip to content

Instantly share code, notes, and snippets.

@drabbytux
Last active September 22, 2020 22:48
Show Gist options
  • Save drabbytux/a49215c6d0ba16c4d096a56212bbc4ce to your computer and use it in GitHub Desktop.
Save drabbytux/a49215c6d0ba16c4d096a56212bbc4ce to your computer and use it in GitHub Desktop.
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
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
Copy link

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
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
Copy link

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
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
Copy link

@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
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
Copy link

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
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
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
Copy link

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
Copy link

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
Copy link

Someone please help.

@koky462
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
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
Copy link

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
Copy link

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
Copy link

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
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
Copy link

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.

@Aj998
Copy link

Aj998 commented Jan 28, 2020

Hi there,
I'm using Masonry theme and have tried all the above given options, however, its not working. Can someone please help. Thanks

@brzy
Copy link

brzy commented Mar 21, 2020

I am using the latest Debut theme (16.5.1) and I cannot get this to fire correctly. When the thumb image is selected the dropdown changes correctly but when I choose to add to cart the first variant is added not the selected color. If I use the dropdown to select a color (default theme behavior) it works fine, just not when the thumbnail image is selected. I have no other modifications to the theme code.
Any help would be much appreciated!

@clemire
Copy link

clemire commented Mar 27, 2020

Not sure if this has been updated/solved for mobile issues in the repo, but what I discovered a year ago and forgot to post back here is that when I used chrome on my pixel 3 to select a thumbnail, it did not fire a click event, but a touch event. So I bound the event handler for each element not just to the click event, but also to the touch events and that fixed my issue.

@lobeg25
Copy link

lobeg25 commented May 2, 2020

The current code worked well for me in the native language of my Shopify, which is english, but did not work when switching to another language, e.g. french.

I could make it work by replacing "return $(this).text()" with "return $(this).val()" in the code.

The .text() is different from language to language, but .val() is invariant.

I use the Pop theme.

@LizWdesign
Copy link

was there an answer for brzy? " -- I am using the latest Debut theme (16.5.1) and I cannot get this to fire correctly. When the thumb image is selected the dropdown changes correctly but when I choose to add to cart the first variant is added not the selected color. If I use the dropdown to select a color (default theme behavior) it works fine, just not when the thumbnail image is selected. I have no other modifications to the theme code.
Any help would be much appreciated!"
I had it working until I downloaded the new Debut theme. Help please! thank you!

@Taoufik0101
Copy link

impossible pour moi, j'ai beau suivre toute la procédure cela ne fonctionne pas! J'utilise également le théme Début

@drabbytux
Copy link
Author

Since Debut is now shipping without JQuery, we are now utilizing a vanilla js model. Here is one that works for newer Debut themes.

https://gist.github.com/drabbytux/7f3f2c57c01fcd4baba98668c9473adc

@Jbest-codes
Copy link

I have implemented 2-way binding however the variant names do not switch to the correct name. Also is there a way to bind multiple photos?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment