• Home
  • Recipes
  • Photography
  • Marketing
  • Technology
  • Home
  • Recipes
  • Photography
  • Marketing
  • Technology
HomeTechnologyOpen SourceShopify Choose Variation By Image Solution
Previous Next

Shopify Choose Variation By Image Solution

Posted by: Noah , August 18, 2016

Hey All,
I’ve been working on a site and couldn’t find a good solution out there for being able to select a product variation by the image you click. So I wrote this. Hope it helps someone.

First off, this goes in the theme.js.liquid file. You should find where your products class is and toss it in there.
Also, you’ll want to go into product.liquid (most likely but will depend on your theme) and find the thumb variations container. From there, you’ll simply add an id ( using image.id ) to each image as they are cycled over.


//get an array of the product variants
 var variantsArray = this.variants;

//create an object associating product variant image id's with variant id. 
 var variantsByImageIdArray = {};
 for(var i=0; i<variantsArray.length; i++){
   variantsByImageIdArray[(variantsArray[i].featured_image.id)] = variantsArray[i];
 }
 //create a click event for each image variant in your container (changing the id to your own id)
 $('#yourThumbsContainer .product-thumbnail img').click( function(){

   // set the variantImage and get it's ID attribute
   var variantImage = $(this);
   var vId = variantImage.attr('id');
   
   // cycle over each image in the array and find the associated variation based on which image was clicked.
   $.each(variantsByImageIdArray, function(i,v){
        if(vId == i){
          // cycle through the selectors and set each option value based on the variation that was clicked
          $.each($('.single-option-selector'), function(i2,v2){
            $(this).val(v.options[i2]);
          });
          
          // Triggering a change will update the variation selected on the shopify product page.  
          $('.Single-option-selector').trigger('change');
        }
   });
 });

Share!
Tweet

Noah

About the author

Related Posts

An Open Source Experience with Students from the University of Minnesota, Morris

An Open Source Experience with Students from the University of Minnesota, Morris I was thrilled ...
Raspberry Pi - Noah Keitel

Raspberry Pi and Geckoboard – A Definitive Guide

Raspberry Pi and Geckoboard – A Definitive Guide Wondering how to get started and get you ...
Nest Thermostat

The Answer To Programmable Thermostats That Never Get Programmed

With the advent of wireless networks widespread in homes across the United States comes the inn ...

Comments

comments

Photography

Copyright © 2019 Noah Keitel
  • Home
  • Recipes
  • Photography
  • Marketing
  • Technology