Shopify themes, liquid, logos, and UX
I have a product with 3 variant. Im trying to create a custom variant picker so i can comply with the pharmacy regulations.
I am stuck at the point after the variant selection, it does not update the variant without a page reload.
I managed to make an autopage reload so it updates the variant, but how can i achieve the same without a page reload?
This is how my script looks like:
<script>
document.addEventListener('DOMContentLoaded', function () {
const optionRows = document.querySelectorAll('.option-row');
const variantInput = document.querySelector('input[name="id"]'); // Shopify's hidden input for variant ID
// Select the first variant by default
let selectedVariantId = document.querySelector('.option-row.selected')?.dataset.variantId;
if (variantInput && selectedVariantId) {
variantInput.value = selectedVariantId;
}
// Add click event listeners to each variant row
optionRows.forEach((row) => {
row.addEventListener('click', function () {
// Remove the "selected" class from all rows
optionRows.forEach((r) => r.classList.remove('selected'));
// Add the "selected" class to the clicked row
this.classList.add('selected');
// Update the selected variant ID
selectedVariantId = this.dataset.variantId;
console.log('Selected Variant ID:', selectedVariantId);
if (variantInput) {
variantInput.value = selectedVariantId;
}
// Update the URL with the selected variant
const params = new URLSearchParams(window.location.search);
params.set('variant', selectedVariantId);
const newUrl = `${window.location.pathname}?${params.toString()}`;
// Reload the page with the updated URL
window.location.href = newUrl;
});
});
// Preselect the variant if it exists in the URL
const urlParams = new URLSearchParams(window.location.search);
const urlVariantId = urlParams.get('variant');
if (urlVariantId) {
const matchingRow = document.querySelector(`.option-row[data-variant-id="${urlVariantId}"]`);
if (matchingRow) {
// Deselect all rows and select the matching row
optionRows.forEach((r) => r.classList.remove('selected'));
matchingRow.classList.add('selected');
// Update the hidden input
if (variantInput) {
variantInput.value = urlVariantId;
}
}
}
});
</script>
Solved! Go to the solution
This is an accepted solution.
Hi @idanperetz,
You can use Javascript's fetch to do this. Refer link
I hope it helps!
This is an accepted solution.
Hi @idanperetz,
You can use Javascript's fetch to do this. Refer link
I hope it helps!
Learn how to build powerful custom workflows in Shopify Flow with expert guidance from ...
By Jacqui May 7, 2025Did You Know? May is named after Maia, the Roman goddess of growth and flourishing! ...
By JasonH May 2, 2025Discover opportunities to improve SEO with new guidance available from Shopify’s growth...
By Jacqui May 1, 2025