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!
Hey Community! As we jump into 2025, we want to give a big shout-out to all of you wh...
By JasonH Jan 7, 2025Hey Community! As the holiday season unfolds, we want to extend heartfelt thanks to a...
By JasonH Dec 6, 2024Dropshipping, a high-growth, $226 billion-dollar industry, remains a highly dynamic bus...
By JasonH Nov 27, 2024