Product variant

AmbraProfumeria
Tourist
5 0 2

Good morning, I run an Expanse-themed online store. When I select a variant the relative image updates correctly, while if I select a different image of the product the selection does not change and remains on the variant of the previous image.

How do I update the variant when I select the relative image?

Thank you

Agostino

Replies 3 (3)

RobDukarski
Shopify Partner
88 15 20

@AmbraProfumeria 

That is likely going to require a bit of Liquid and JavaScript to setup but the general idea is that you would loop through the variants when you are outputting the images to see if there is a variant with that matching image associated with it and then add some code to the image that ties it to the variant such as the variant's ID. From there you will want to add some JavaScript that will listen for a certain event of the image and when that event occurs grab the data that is tied to the variant and then select that variant based on the 1:1 match.

It should only require a few lines of JavaScript to set up, something like this:

window.addEventListener('load', function() {
  const productVariantImages = document.querySelectorAll('.product__thumb[data-variant-id]');

  if (!!(productVariantImages) && productVariantImages.length > 0) {
    productVariantImages.forEach((variantImage) => {
      variantImage.addEventListener('click', function(event) {
        event.preventDefault();
        const variantId = this.dataset.variantId;
        const variantLabel = document.querySelector(`.variant__button-label[data-variant-id="${variantId}"]`);

        if (!!(variantLabel)) {
          variantLabel.click();
        }
      });
    });
  }
});


That's not going to work as-is. You will need to add the "data-variant-id" attribute and value to the variant image URL and the variant's input label and frankly I did not test it within the theme itself because it has a cost associated to purchase the theme before I can even touch its code.

Hope that helps!

- Rob Dukarski
Helping to make commerce better for everyone!
AmbraProfumeria
Tourist
5 0 2

Hello Rob,

Thanks for the information, I will try to enter the code and test it.

Thank you very much,

Agostino

 

RobDukarski
Shopify Partner
88 15 20

@AmbraProfumeria 

I want to remind you that you would also need to add the "data-variant-id" attribute to the elements I reference within the JavaScript (based on a demo store that uses the theme). I tested it on my end with my web browser's development tools and the code should work if those attributes are in place (assuming no other code of your store may affect the functionality, like a third-party App's code).

Please let me know if you are able to get it to work based on my recommended solution. Thanks!

- Rob Dukarski
Helping to make commerce better for everyone!