TLDR;
I have a URL that has a ending bit that changes upon a option select change:
www.mywebsite.com?variant=13390743207991
or
?variant=13400659984439
I’m wondering if there is a way to detect this change. I’ve been able to do this with a setInterval
and just grab the URL ever 0.5 seconds to detect a change, but is there a more effective way than this?
The full story
I’m fairly new to this area of javascript, so correct me if I’m wrong.
I’m developing some work for a Shopify website. From what I can see, Shopify offers a product variant selector for a specific product, in which it is populated dynamically changing the selected product and product price.
Upon adding new classes to the selection form I realize they get removed automatically upon creation making it difficult for me to check on my end if a new option is selected. An example of it looks something like this:
<select name="id" id="productSelect-{{ product.id }}" class="product-single__variants">
{% for variant in product.variants %}
{% if variant.available %}
<option {% if variant == current_variant %} selected="selected" {% endif %} value="{{ variant.id }}" data-sku="{{ variant.sku }}">{{ variant.title }}</option>
{% else %}
<option>
{{ variant.title }} - {{ 'products.product.sold_out' | t }}
</option>
{% endif %}
{% endfor %}
</select>
I have created a utility to detect geolocation on user vistior to adjust the price of the product accordingly (USD, CAD etc.).
Considering I’m having trouble detecting if a variant has changed outside of Shopify’s bubble, I’m having trouble adjust the displayed price once the varient changes. It is originally adjust through an assignment variable within the liquid code.
I do notice, however, the URL of the page changes upon variant change:
?variant=13390743207991
or
?variant=13400659984439
That extra bit gets tagged on the end of the URL.
I was wondering if there’s any way to detect this URL change that way I could adjust the price on my end when a variant is selected.
2
Answers
Have you tried location-bar:
If you’re using the default shopify script, use the callback they provide. More info here.