In my product have 3 main variants
- Frame Color
- Lens Color
- Lens Clarity
Am trying to do When user click on “Light Pro Variation” then “a new section will show information”
<script>
document.addEventListener("DOMContentLoaded", function () {
const urlParams = new URLSearchParams(window.location.search);
const variantId = urlParams.get('variant');
const lightProVariantId = "41681500831821"; // Replace with your real ID
console.log("Variant ID from URL:", variantId);
if (variantId === lightProVariantId) {
alert("yes");
document.getElementById('your-div-id').style.display = 'block';
} else {
alert("no");
document.getElementById('your-div-id').style.display = 'none';
}
});
</script>
JavaScript can’t identity what is selected. Any idea what need to do. Please help!!
Thanks
Hey @Sushovan_Bhowmik, variants and product options are different, depending on the selected combination of product options a different variant will ultimately be selected.
Typically I look for a “select element” of variants and modify it to include extra details I may need if any. Then I hook into the change functionalily related to it so that when the variant changes I can pull the necessary data, for example fetch a section using the Section Rendering API and then inject what I want from it. For example to show variant-specific details.
Hi @Sushovan_Bhowmik ,
Your script checks the ?variant= URL parameter — which works if the variant is selected by a link that includes ?variant=ID.
If the page loads with ?variant=41681500831821 in the URL → your alert(“yes”) shows and the section appears.
But if the user changes the variant by clicking on the product page selector, the variant parameter doesn’t update automatically — so your script doesn’t detect it.
Try below script
<div id="light-pro-info" style="display: none;">
This is info for Light Pro.
</div>
<script>
document.addEventListener("DOMContentLoaded", function () {
const lightProVariantId = "41681500831821"; // Replace with your real ID
const infoSection = document.getElementById('light-pro-info');
function toggleInfo(variantId) {
if (variantId === lightProVariantId) {
infoSection.style.display = 'block';
} else {
infoSection.style.display = 'none';
}
}
const urlParams = new URLSearchParams(window.location.search);
const variantId = urlParams.get('variant');
toggleInfo(variantId);
document.addEventListener('change', function (e) {
if (e.target.matches('form[action*="/cart/add"] select[name="id"]')) {
const selectedId = e.target.value;
toggleInfo(selectedId);
}
});
// If your theme uses `variant:change` event:
document.addEventListener('variant:change', function (e) {
const selectedId = e.detail.variant.id;
toggleInfo(String(selectedId));
});
});
</script>