Last active
October 29, 2018 08:00
-
-
Save freakdesign/7363419 to your computer and use it in GitHub Desktop.
Javascript snippet to help auto select a Shopify variant from a hash.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
/* | |
re: http://ecommerce.shopify.com/c/ecommerce-design/t/land-on-specific-variant-when-loading-product-page-147793 | |
Assumes: | |
-------- | |
* that you are calling the javascript once the select element is available | |
* you have a select element on the page like: | |
<select name="id" id="select-variant"> | |
<option value="201565932" data-sku="some_unique_sku">Variant one</option> | |
<option value="201565932" data-sku="some__other_unique_sku">Variant two</option> | |
</select> | |
Usage: | |
------ | |
The resulting url to use would be in a format like: | |
http://www.my-shopify-store.com/collection/product#some__other_unique_sku | |
The code would be added to your main theme.js, or to the bottom of your product.liquid file. | |
Sidenote: | |
--------- | |
You don't have to use the data-sku. You just need some way of making each option unique so you can find it. | |
*/ | |
var initSelect = function(){ | |
if(window.location.hash) { | |
var s = $('#select-variant'), | |
h = window.location.hash.substring(1); | |
s.find('option').each(function() { | |
var t = $(this); | |
if(t.attr('data-sku') == h){ | |
$('#select-variant-option-0').val(t.text()); | |
} | |
}); | |
} | |
} | |
initSelect(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment