Skip to content

Instantly share code, notes, and snippets.

@dpw1
Created March 19, 2024 18:58
Show Gist options
  • Save dpw1/a11b34239500807dc9cf72e3e44385a4 to your computer and use it in GitHub Desktop.
Save dpw1/a11b34239500807dc9cf72e3e44385a4 to your computer and use it in GitHub Desktop.
{% 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