Skip to content

Instantly share code, notes, and snippets.

@erwanriou
Last active December 8, 2021 17:31
Show Gist options
  • Save erwanriou/88f8c6b2b6aa31e61f4bd845e0899042 to your computer and use it in GitHub Desktop.
Save erwanriou/88f8c6b2b6aa31e61f4bd845e0899042 to your computer and use it in GitHub Desktop.
// HANDLE THE EVENT HANDLER FUNCTION
const handleProductsTotalPriceUpdate = () => {
const getProductsTotal = () => {
const products = document.getElementsByClassName(
"woocommerce-grouped-product-list-item"
);
const totals = Object.values(products)
.map((p) => {
// GET QUANTITIES
const quantity =
parseInt(
p.getElementsByClassName("input-text qty text")[0].valueAsNumber,
10
) || 0;
// GET AND FORMAT PRICES
const price = p.getElementsByTagName("bdi")[0].innerText;
const formatedPrice = parseInt(
price.split("DKK")[0].replace(/\./g, ""),
10
);
// GET TOTALS
const total = formatedPrice * quantity;
return total;
})
.reduce((a, b) => a + b, 0);
return totals;
};
// INJECT DISCOUNT
const injectHtml = () => {
const totals = getProductsTotal();
let tabs = document.getElementsByClassName("price product-page-price ");
const previousContent = tabs[0].innerHTML;
if (
totals > 0 ||
tabs[0].innerHTML.split(":")[0] === '<span class="price-prefix">Total'
) {
tabs[0].innerHTML = `<span class="price-prefix">Total:</span><span class="woocommerce-Price-amount amount"><bdi>${totals},00 <span class="woocommerce-Price-currencySymbol">DKK</span></bdi></span>`;
}
};
injectHtml();
};
// HANDLE THE TRIGGER
const handleTriggers = () => {
const inputWrapper = document.getElementsByClassName(
"quantity buttons_added"
);
const inputs = Object.values(inputWrapper).map((w) => {
const inputs = w.getElementsByTagName("input");
Object.values(inputs).map((i) => {
i.onchange = () => handleProductsTotalPriceUpdate();
});
});
};
handleProductsTotalPriceUpdate();
handleTriggers();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment