Skip to content

Instantly share code, notes, and snippets.

@joahg
Last active September 18, 2015 03:51
Show Gist options
  • Save joahg/e2b0a0f4c9503966f538 to your computer and use it in GitHub Desktop.
Save joahg/e2b0a0f4c9503966f538 to your computer and use it in GitHub Desktop.
$(function() {
var groupImages = {},
api_token = '';
for (i in groupIds) {
groupImages[groupIds[i].id] = { variants: {} };
$('[data-id="' + groupIds[i].id.toString() + '"] select[name*="ProductGroupVariants"] option').each(function() {
groupImages[groupIds[i].id][$(this).attr('value')] = '';
});
}
var getVarImg = function(id, v) {
if (!groupImages[id][v] || groupImages[id][v] === '') {
$.ajax({
url: 'https://' + window.location.hostname + '/api/v1/product_variants?product_id=' + id.toString() + '&id=' + v.toString(),
type: 'GET',
dataType: 'JSON',
async: false,
headers: {
'Content-type': 'application/json',
'X-AC-Auth-Token': api_token
},
success: function(d) {
groupImages[id][v] = d['variants'][0]['swatch_file'];
},
error: function(d) {
getVarImg(id, v);
}
});
}
return groupImages[id][v];
};
$('select[name*="ProductGroupVariants"]').on('change', function() {
var $p = $(this).closest('[data-id]'),
id = $p.attr('data-id'),
v = $(this).find('option:selected').attr('value');
$p.find('.thumbnail img').attr('src', getVarImg(id, v));
});
$('select[name*="ProductVariations"]').first().on('change', function() {
var _v = $(this).find('option[value="' + $(this).val() + '"]').text();
$('select[name*="ProductGroupVariants"]').each(function() {
$(this).val($(this).find('option:contains(' + _v + ')').attr('value')).trigger('change');
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment