Skip to content

Instantly share code, notes, and snippets.

@bpmutter
Created August 2, 2022 02:07
Show Gist options
  • Save bpmutter/80c95828fe67a2e03cfda6342f9a8df6 to your computer and use it in GitHub Desktop.
Save bpmutter/80c95828fe67a2e03cfda6342f9a8df6 to your computer and use it in GitHub Desktop.
<script>
const orderItems = {};
let totalOrderItems = 0;
let itemsInBox = document.getElementById("total-items-in-box")?.innerHTML;
itemsInBox = !isNaN(itemsInBox) ? parseInt(itemsInBox) : null;
const orderItemDisplay = document.getElementById("current-items-in-box");
const addToCartButton = document.getElementById("add-to-cart");
const buyNowButton = document.getElementById("buy-now");
if(itemsInBox){
disableButtons();
const selectors = document.querySelectorAll(".boxitemnumber");
selectors.forEach((itemNumber) => {
itemNumber.addEventListener("change", (e)=> {
orderItems[e.target.name] = parseInt(e.target.value);
totalOrderItems = Object.values(orderItems).reduce((prev, curr) => prev + curr);
orderItemDisplay.innerHTML = totalOrderItems;
if(totalOrderItems === itemsInBox){
enableButtons();
} else {
disableButtons();
}
});
});
}
function enableButtons(){
addToCartButton.disabled = false;
buyNowButton.disabled = false;
addToCartButton.classList.remove("disabled");
buyNowButton.classList.remove("disabled");
}
function disableButtons(){
addToCartButton.disabled = true;
buyNowButton.disabled = true;
addToCartButton.classList.add("disabled");
buyNowButton.classList.add("disabled");
}
addToCartButton.addEventListener("click", () => {
if(!addToCartButton.disabled && totalOrderItems === itemsInBox) {
saveBoxToLocalStorage(itemsInBox, orderItems);
setTimeout(disableButtons, 500);
}
});
function saveBoxToLocalStorage(numItemsInBox, boxContents){
const baseName = `${numItemsInBox}_piece_box_`;
let boxAtSizeNum = 0;
while(localStorage.getItem(`${baseName}${boxAtSizeNum}`)) {
boxAtSizeNum++;
}
localStorage.setItem(baseName + boxAtSizeNum.toString(), JSON.stringify(boxContents));
}
const checkoutTextArea = document.getElementById("all-products-info");
if(checkoutTextArea) {
const allBoxes = { ...localStorage };
for (const box in allBoxes) {
allBoxes[box] = JSON.parse(allBoxes[box]);
}
const boxKeys = Object.keys(allBoxes);
const boxNames = boxKeys.map((key) => {
const keySegments = key.split("_");
return keySegments[0] + " Piece Box #" + keySegments[3] + ":\n";
});
const boxValues = Object.values(allBoxes);
const boxItems = boxValues.map((boxItemsByQuantity) => {
let items = "";
for (const [product, quantity] of Object.entries(boxItemsByQuantity)) {
items += `- ${product}: ${quantity}\n`;
}
return items;
});
let allBoxesInfo = "";
boxNames.forEach((boxName, i) => {
const boxInfo = boxName + boxItems[i] + "\n---\n\n"
allBoxesInfo += boxInfo;
});
checkoutTextArea.innerHTML = allBoxesInfo;
}
// place order clear local storage
const placeOrderButton = document.getElementById("place-order-button");
if(placeOrderButton) {
placeOrderButton.addEventListener("click", () => {
localStorage.clear();
});
}
// remove items of type
document.getElementById("cart-button")?.addEventListener("click", setUpRemoveItemsInCart);
document.getElementById("add-to-cart")?.addEventListener("click", setUpRemoveItemsInCart);
function setUpRemoveItemsInCart(){
setTimeout(()=> {
const itemsInCart = document.querySelectorAll(".open-cart-items");
console.log(itemsInCart);
if(itemsInCart.length){
const itemsInLocalStorage = Object.keys({ ...localStorage });
itemsInCart.forEach((cartItem) => {
cartItem.addEventListener('click', (e)=>console.log(e.target))
const itemTitle = Array.from(cartItem.children).find((child) => child.classList.contains("cart-item-title")).innerHTML;
itemTitleLowerUnderscore = itemTitle.replaceAll(" ", "_").toLowerCase();
const matchingItemsInLocalStorage = itemsInLocalStorage.filter((item) => item.includes(itemTitleLowerUnderscore));
let removeButton = Array.from(cartItem.children).find((child) => child.classList.contains("remove-button"));
removeButton = removeButton.children[0];
removeButton.addEventListener("click", () => {
matchingItemsInLocalStorage.forEach((item) => localStorage.removeItem(item));
}, true);
});
}
}, 350);
}
// clear local storage when on order confirmation page and no items in cart
const orderConfirmationPage = document.getElementById("order-confirmed");
const itemsInCart = document.getElementById("cart-quantity")?.innerHTML;
if(orderConfirmationPage && itemsInCart != false) { // only shallow equal b.c checking if undefined or '0', which are both falsy
localStorage.clear();
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment