Skip to content

Instantly share code, notes, and snippets.

@atikju
Created October 23, 2018 16:22
Show Gist options
  • Save atikju/eaff20f0fb506e4eadc5feb9d469a916 to your computer and use it in GitHub Desktop.
Save atikju/eaff20f0fb506e4eadc5feb9d469a916 to your computer and use it in GitHub Desktop.
Shopify - change variant on Product thumbnail image click or change
<script>
$(document).ready(function(){
/*
STEPS:
1. Grab the img id from the src on gallery thumb click
2. loop thru the radio button images and grab the img src
2a. click the button that's it!
*/
/*
As the gallery is using flickity slider, we need to find when the gallery is ready!
Hence, we are running an interval and checking the point when the gallery is available
in the DOM nodes.
*/
var galleryChecker = setInterval(function(){
if($('.gallery-cell').length > 0){
console.log('DOM is ready BOSS');
//wait for a second
setTimeout(function(){
//run the procedure
$('.gallery-cell img').on('click', function(){
//STEP 1
var theThumbImg = $(this).attr('src');
console.log(theThumbImg);
//STEP 2
var imgUrl = '';
//run a for loop for each swatch input. dev_input is a custom class added to the swatch input
$('.swatch_options .swatch').eq(0).find('.dev_input').each(function(){
imgUrl = $(this).data('dev-id'); //added data-dev-id="{{ variant.img | img_url: 'SwatchImgSize' }}" in the swatch radion input loop
//STEP 2a
if(theThumbImg == imgUrl){
console.log('matched');
$(this).trigger('click');
return false;
}
});
});
//arrow click
$('.flickity-prev-next-button').on('click', function(){
//STEP 1
var featSrc = $('.gallery-cell.is-selected img').data('dev-hook');
var theThumbImg = featSrc;
console.log(theThumbImg);
//STEP 2
var imgUrl = '';
$('.swatch_options .swatch').eq(0).find('.dev_input').each(function(){
imgUrl = $(this).data('dev-id');
//STEP 2a
if(theThumbImg == imgUrl){
console.log('matched');
$(this).trigger('click');
return false;
}
});
});
}, 1000);
//clear interval
clearInterval(galleryChecker);
}
}, 1);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment