Thanks for the hint. This is my current solution:
- Loop over all variants and create the correct HTML with data-variant-id, hide it with display: none
{% for variant in product.variants %}
{%- if variant.available -%}
Content Available
{%- else -%}
Content Not Available
{%- endif -%}
{% endfor %}
- Detect current variant and show the right content
// Add observer to detect url change. This will call "onUrlChange()"
let lastUrl = location.href;
new MutationObserver(() => {
const url = location.href;
if (url !== lastUrl) {
lastUrl = url;
onUrlChange();
}
}).observe(document, {subtree: true, childList: true});
// Initialise the correct variant on page load
updateVariants();
// Update variant on url change
function onUrlChange() {
updateVariants();
}
function updateVariants()
{
// get the current variantId (or null if initial page load)
const variantId = getCurrentVariantId();
// get all created variant contents
const elements = document.querySelectorAll("[data-variant-id]");
let first = true;
elements.forEach(el => {
let display = 'none'
// either show the one for the current variantId OR the first one, if no variantId is given (first page load)
if ((variantId && el.getAttribute('data-variant-id') === variantId) || (!variantId && first)) {
display = 'block';
}
first = false;
el.style.display = display
})
}
// get the variantId from the URL (or null if initial page load)
function getCurrentVariantId() {
const params = new URLSearchParams(window.location.search)
let variantId = null;
if (params.has("variant")) {
variantId = params.get("variant");
}
return variantId;
}