We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.
If you're still in need, here is a solution I found worked after running into the same issue:{% for variant in product.variants %}
<div class="yagi-variant-description" data-variant-id="{{ http://variant.id }}" style="display:none;">
{{ variant.metafields.custom.variant_description | metafield_tag }}
</div>
{% endfor %}
<script>
function yagiHideAllVariantDescriptionExcept(variant){
document.querySelectorAll('.yagi-variant-description').forEach(el => {
el.style.display = 'none';
});
const descriptionEl = document.querySelector(`.yagi-variant-description[data-variant-id="${variant}"]`);
if (descriptionEl){
descriptionEl.style.display = 'block';
}
}
document.addEventListener("DOMContentLoaded", () => {
// Initial check
const urlParams = new URLSearchParams(window.location.search);
const initialVariant = urlParams.get('variant');
if(initialVariant) {
yagiHideAllVariantDescriptionExcept(initialVariant);
}
// Set up observer for changes
const observer = new MutationObserver((mutations) => {
const urlParams = new URLSearchParams(window.location.search);
const variantId = urlParams.get('variant');
if(variantId) {
yagiHideAllVariantDescriptionExcept(variantId);
}
});
observer.observe(document.body, {
subtree: true,
childList: true
});
});
</script>
Thanks Alex!
Thank you Alex! I have tested the MutationObserver code and it seems to work well across multiple themes, I have updated the post to include the MutationObserver code and credited your name there.
Great! And thank you for the original article. It was a surprise to find the variant functionality wasn't built in and this was super helpful.
Thanks for the help, I use the exact code you published and it works purrrrfectly.
This works great on Impulse theme, after hours of searching it's the only solution i found which updates metafield output every time a different variant is selected, and without refreshing the page.
Do you think there is any way of using this output in a conditional manner to change the content of page depending on the selected variant?
I was for example trying to do :
{% if variant.metafields.custom.variant_name == 'VariantOne' %}
<p>My Content</p>
{% endif %}
Thank you very much for your help 🙂
Update!
This is excellent - however it seems to not work quite right for me.
All of my variants are showing the last variant description I've added.
I was incorrect about the product variant descriptions and how they appear.
The product variation that shows for ALL variations is the variation description of whichever variation the user is on when the shopify page is refreshed.
So if I refresh the store on the 3rd variant - all variants get the 3rd variant description.
I'm not sure what is wrong with the code so that the variant description changes to when the user clicks on different variants in the shopify store.