Shopify / slate

Slate is a toolkit for developing Shopify themes. It's designed to assist your workflow and speed up the process of developing, testing, and deploying themes.
https://shopify.github.io/slate
MIT License
1.28k stars 364 forks source link

Is there a reliable way of getting the variant ID or product ID (if no variants) through JS? #1035

Open adrianocr opened 5 years ago

adrianocr commented 5 years ago

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 }})

ConduciveMammal commented 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');
RustyDev commented 5 years ago

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:

https://github.com/Shopify/starter-theme/blob/b15000a50877e7526b32a4580c2a7712adfcec89/src/scripts/sections/product.js#L68

tom-it commented 4 years ago

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)

ivalsaraj commented 4 years ago

@tom-it But I've found in some stores have selectedVariantId value is blank

image