How to display only selected variant metafields with JavaScript?

How to display only selected variant metafields with JavaScript?

LeviSchneiderCS
New Member
6 0 0

Hi, 

 

I'm trying to add variant metafields to my product page so that they'll change when the variant is selected from the drop down menu. I was able to add the metafields no problem, but all of them are displayed at the same time. Can someone help out with how to add javascript so that only the metafields for the SELECTED variant will be displayed? 

 

I know to toggle the display in CSS after the fact using the ".active" tag but I have no idea where to begin with coding the javascript portion. 

Screen Shot 2021-12-10 at 11.31.10 AM.png

Replies 4 (4)

Finer
Shopify Partner
2626 554 916

@LeviSchneiderCS Have you tried removing the Loop?

 

 {% for variant in product.variants %}

 

- Did my answer help? Mark my post with a like
- Did I solve your problem? Mark my post as an accepted solution.
- You need professional help? Contact our Shopify Partner Agency
LeviSchneiderCS
New Member
6 0 0

I have. Removing the loop removes all of the metafield data on the product page.

Mircea_Piturca
Shopify Partner
1548 44 349

Your code will display all descriptions assigned in the variant metafields. 

 

You need to:

1. Display the metafield for the first selected or available variant

2. Store all metafield values in a JavaScript variable. Can be an object from where you can access them based on the variant ID.

3. Add an event listener on your theme variant select (swatch, drawdown, whatever you have...).

4. This event listener callback function will get the selected variant ID, fetch the metafield data we stored at point 2 and update the "variant-dimensions" element.

 

Hope it helps

Finally—Add variant descriptions to your products
LeviSchneiderCS
New Member
6 0 0

Ok I'm trying to do this (but with basically zero knowledge of javascript) and I'm hoping you could elaborate a little further in regards to the following:

 

1. Will establishing a variable with the variant ID be transferrable to other pages? Or will it be product-specific?

2. What is the syntax for the variable? I have the variant IDs but how do I grab the specific metafields? Would it look something like this?:

var variantDimensions= [ "{{variant.metafields.my_fields.length.value}}", "{{variant.metafields.my_fields.depth.value}}", "{{variant.metafields.my_fields.height.value}}"];

3. what is the syntax for the event listener? Would it look like this?:

document.addEventListener('popover');