Please help me with this variant metafield code fix

Hi, I’m using Shopify 2.0 Horizon. I’m setting up a furniture store so I need a Bed to have variants such as Queen and King which have different measurements. I’ve added a custom responsive accordion block to my product template. Each accordion can be connected to a product metafield but i need it to be connected to a variant metafield. I’ve added a custom.measurements variant metafield. I have been able to tweak the code to connect it to a variant metafield but my issue is when the king or queen variant is clicked, it doesn’t change the measurements unless I refresh the page. Is there a way to have this load naturally when the variant is clicked or have it reload the page so the correct measurement is shown? Any help would be appreciated (im not good with code)

https://sharetext.io/1c5030ce

This is my store: https://pxvy56-w0.myshopify.com/
password is mike

By default, Horizon updates only a handful of properties on product page with variant selection.
And it is not possible to use variant metafields as Dynamic sources.

It’s possible though to extend theme functionality by adding a “Custom liquid” block which will update its content on variant change.

You can do it like this – Add an “Accordion Row” block, but instead of default text blocks add a “Custom liquid” one:

Into “Custom liquid” block paste the code like this – you need to change it to use your metafield:

{% # the ID parameter must use uniq on the page %}
<variant-data class="rte" id="availability-{{section.id}}">
  {% #  output your metafield value %}
  {{ closest.product.selected_or_first_available_variant.metafields.availability["14-Lyndon-Street"] }}
</variant-data>

<script>
  if (!customElements.get('variant-data')) {
    class VariantData extends HTMLElement {
      constructor() { super(); }
      connectedCallback(){
        document.addEventListener('variant:update', ({detail}) => {
          const newContent = detail.data?.html?.getElementById(this.id)?.innerHTML;
          if (newContent) this.innerHTML = newContent;
        });
      }
    }
    customElements.define('variant-data', VariantData )
  };
</script>

The Javascript code here will listen to events fired by the Horizon theme code and update this variant-data element accordingly.

See it working here.

Similar solution for Dawn family themes: Variant Metafield reference is Giving Invalid Error - #3 by tim_1


if my post is helpful, please like it ♡ and mark as a solution -- this will help others find it

Thank you very much. With some tweaking to my custom accordion to include a liquid it worked! Appreciate the help!!