Open adrianocr opened 5 years ago
I usually grab it via data-attributes.
<div id="variant" data-variant="{{ product.selected_or_first_available_variant.id }}"></div>
console.log($('#variant').data('variant');
Another option is to read it from window location:
window.location.search.split('variant=')[1]
The url is updated when changing variants.
If you're using the starter theme, there's a listener on form option change:
I'm still having a hard time getting this from a 'normal' change event. so I use this to get the selected variantId from JS console.log(ShopifyAnalytics.meta.selectedVariantId); (will be empty if variant is out of stock)
@tom-it But I've found in some stores have selectedVariantId value is blank
I developed a little script to add items to the cart via an ajax request. Works perfectly if I supply it the variant ID.
However, I'm having a hard time getting the variant ID through JS. I know Shopify is doing something when options are changed because I see the variant change in the address bar. Is there a way to tap into that to get the current variant ID through JS? Something like a
window.variant_id
variable or something that gets exposed? Ideally this var should be set as soon as the DOM is done loading, even if an option hasn't been selected yet (essentially the same as liquid's{{ product.selected_or_first_available_variant.id }}
)