Instantly share code, notes, and snippets.
Created
March 19, 2024 18:58
-
Star
0
(0)
You must be signed in to star a gist -
Fork
0
(0)
You must be signed in to fork a gist
-
Save dpw1/a11b34239500807dc9cf72e3e44385a4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% if request.page_type == 'product' %} | |
<script> | |
window.buttonPriceHandlerVariants = [ | |
{% for variant in product.variants %} | |
{ | |
id: parseInt(`{{ variant.id }}`), | |
price: `{{ variant.price | money }}` | |
}, | |
{% endfor %} | |
] | |
window.ezfyButtonPriceHandler = window.ezfyButtonPriceHandler || {}; | |
ezfyButtonPriceHandler = (function () { | |
const LOADING_DELAY = 50; | |
function sleep(ms) { | |
return new Promise(resolve => setTimeout(resolve, ms)); | |
} | |
function getVariantID() { | |
const $id = document.querySelector(`[id*='product-form'] > input:nth-child(3)`); | |
if (!$id) { | |
return null; | |
} | |
const _id = $id.getAttribute("value"); | |
if (!_id) { | |
return; | |
} | |
const id = parseInt(_id); | |
if (!/\d\d\d/.test(id)) { | |
return null; | |
} | |
return id; | |
} | |
function handleDropdownChange() { | |
const $dropdowns = document.querySelectorAll(` [class*='product__info'] variant-selects select`); | |
if (!$dropdowns){ | |
return | |
} | |
for (var each of $dropdowns){ | |
each.addEventListener("change", async function(e){ | |
await sleep(LOADING_DELAY); | |
updatePrice(); | |
}); | |
} | |
} | |
function handleSwatchChange(){ | |
const $radios = document.querySelectorAll(`[class*='product-form'] [type='radio']`) | |
if (!$radios) { | |
return; | |
} | |
for (var $radio of $radios) { | |
$radio.addEventListener("click", async function() { | |
await sleep(LOADING_DELAY); | |
updatePrice(); | |
}); | |
} | |
} | |
async function updatePrice(){ | |
const id = getVariantID(); | |
const found = buttonPriceHandlerVariants.find(e => e.id === id); | |
const $button = document.querySelector(`.ezfyButtonPrice`); | |
if (!$button){ | |
return; | |
} | |
$button.textContent = ` - ${found.price}` | |
} | |
return { | |
init: function () { | |
document.addEventListener("DOMContentLoaded", function () { | |
handleSwatchChange(); | |
handleDropdownChange(); | |
}); | |
window.addEventListener("resize", function () {}); | |
window.addEventListener("load", function () {}); | |
window.addEventListener("scroll", function () {}); | |
}, | |
}; | |
})(); | |
ezfyButtonPriceHandler.init(); | |
</script> | |
{% endif %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment