Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bjornbennett/e16a6712e27c1b620b6b96c913092a34 to your computer and use it in GitHub Desktop.
Save bjornbennett/e16a6712e27c1b620b6b96c913092a34 to your computer and use it in GitHub Desktop.
Shopify Liquid - Some themes that I have used, wouldn't show which variant you were viewing when on it's product page, or wouldn't update when you changed the variant. For various reasons, I needed this information to be available within the URL. This snippet updates the URL when the options are changed. Super helpful.
<!-- ================================== NOTES ============================================= -->
<!-- Print out the variant titles and ids to a hidden div from which to reference -->
<!-- Also strips unnecessary spaces on both sides of the string-->
<div class="btc_container" style="display: none;">
{% for variant in product.variants %}
{% if variant.available %}
{%assign vt1 = variant.title | split: '/' | first | strip %}
{%assign vt2 = variant.title | split: '/' | last | strip %}
<span class="btc-variant-container" data-prod-option-1="{{vt1}}" data-prod-option-2="{{vt2}}" data-var-id="{{variant.id}}">{{vt1}}^{{vt2}}</span>
{% endif %}
{%endfor%}
</div>
<script>
// ============== NOTES ===========================
//
// If a theme doesn't push variant info to the url,
// this will crosscheck the option values of the first select box,
// and the option values of the second select box
// and check them against the product variants
// that are output to containers with the class .btc-variant-containers
function checkVariantUrl(){
// set variables, check values
var btc_find1 = $('select[data-option="option1"]').val(),
btc_find2 = $('select[data-option="option2"]').val(),
btc = $('.btc-variant-container');
if( btc_find2 == undefined ){
// *** If there's only one dropdown
btc.each(function(){
// *** cycle through each btc-variant-container div
var btc_prod1 = $(this).data('prod-option-1');
// *** when it finds a match
if( btc_prod1 == btc_find1 ){
var btc_var_id = $(this).data('var-id');
console.log( btc_prod1, btc_var_id );
// *** edit url to add information to
window.history.pushState('', '', '?variant=' + btc_var_id);
}
});
} else {
// *** If there's two dropdowns
btc.each(function(){
// *** cycle through each btc-variant-container div
var btc_prod1 = $(this).data('prod-option-1'),
btc_prod2 = $(this).data('prod-option-2');
// *** when both options match
if( btc_prod1 == btc_find1 && btc_prod2 == btc_find2 ){
var btc_var_id = $(this).data('var-id');
console.log( btc_prod1, btc_prod2, btc_var_id );
// *** edit url to add information to
window.history.pushState('', '', '?variant=' + btc_var_id);
}
});
}
}
checkVariantUrl();
$('select.single-option-selector').change(function(){
checkVariantUrl();
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment