Created
April 2, 2022 11:55
-
-
Save singhkunal2050/76f425324fd0013ee278b2af85246cfc 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
var client = ShopifyBuy.buildClient({ | |
domain: "yourdomain.myshopify.com", | |
storefrontAccessToken: "ccccasaff694f5f274f11ca7a6712zass", | |
}); | |
function addProducttoLocalStorage(lineItem) { | |
if (!localStorage.lineItems) localStorage.setItem("lineItems", []); | |
let templineItems = [...lineItem].flat(); | |
localStorage.lineItems = JSON.stringify(templineItems); | |
render(); | |
} | |
function createCheckoutLinkAndRedirect(checkout) { | |
let lineItems = JSON.parse(localStorage.lineItems); | |
try { | |
client.checkout.create().then((checkout) => { | |
localStorage.setItem("checkout_id", checkout.id); | |
}); | |
client.checkout | |
.addLineItems(localStorage.checkout_id, lineItems) | |
.then((checkout) => { | |
console.log("Add Prods to CheckOut Instance"); | |
console.log(checkout); | |
window.open(checkout.webUrl, "_blank").focus(); | |
document.querySelector(".cart-action-wrapper img").style.display = | |
"none"; | |
}); | |
} catch (err) { | |
console.log(err); | |
alert("Something Went Wrong. Please retry."); | |
document.querySelector(".cart-action-wrapper img").style.display = | |
"none"; | |
} | |
} | |
function render() { | |
renderCart(); | |
renderCartProducts(); | |
} | |
function renderCart() { | |
document.querySelector(".cart sup").innerHTML = localStorage.lineItems | |
? JSON.parse(localStorage.lineItems).length | |
: checkout.lineItems.length; | |
} | |
function renderCartProducts() { | |
let cartItemsWrapper = document.querySelector(".cart-items"); | |
let lineItems = JSON.parse(localStorage?.lineItems); | |
let html = ""; | |
document.querySelector(".check-out").style.display = "flex"; | |
lineItems.forEach((lineItem) => { | |
html += ` | |
<div class="cart-item" data-product-id="${lineItem.variantId}" > | |
<div class="cart-item-img"> | |
<img src="${lineItem.customAttributes[2].value}" alt=""> | |
</div> | |
<div class="cart-item-details"> | |
<div class="cart-item-title"> | |
${lineItem.customAttributes[0].value} | |
</div> | |
<div class="cart-item-inner-wrapper"> | |
<div> | |
<div class="cart-item-price"> | |
$${( | |
parseFloat(lineItem.customAttributes[1].value) * | |
parseFloat(lineItem.quantity) | |
).toFixed(2)} | |
</div> | |
<div class="cart-item-quantity-wrapper"> | |
<p>Quantity</p> | |
<button class="calculate" data-operation="subtract">-</button> | |
<span class="cart-item-quantity">${ | |
lineItem.quantity | |
}</span> | |
<button class="calculate" data-operation="add">+</button> | |
</div> | |
</div> | |
<div class="cart-item-delete-wraper"> | |
<button class="delete-cart-item">Delete Item</button> | |
</div> | |
</div> | |
</div> | |
</div>`; | |
}); | |
if (lineItems == undefined || lineItems.length == 0) { | |
document.querySelector(".check-out").style.display = "none"; | |
html = ` | |
<h1 class="cart-message" >Cart is Empty</h1> | |
`; | |
} | |
cartItemsWrapper.innerHTML = html; | |
} | |
function updateProductsQuantity(variantId, operation, quantity = 1) { | |
let lineItems = JSON.parse(localStorage.lineItems); | |
lineItems.forEach((lineItem) => { | |
if (lineItem.variantId == variantId) { | |
if (operation == "add") { | |
lineItem.quantity += quantity; | |
} else if (operation == "subtract") { | |
lineItem.quantity -= quantity; | |
} | |
} | |
}); | |
lineItems = lineItems.filter((lineItem) => lineItem.quantity > 0); | |
localStorage.lineItems = JSON.stringify(lineItems); | |
render(); | |
} | |
function deleteCartItem(variantId) { | |
let lineItems = JSON.parse(localStorage.lineItems); | |
lineItems = lineItems.filter( | |
(lineItem) => lineItem.variantId != variantId | |
); | |
localStorage.lineItems = JSON.stringify(lineItems); | |
render(); | |
} | |
// listen for cart events | |
document.querySelector("body").addEventListener("click", (e) => { | |
if (e.target.matches(".calculate")) { | |
let operation = e.target.dataset.operation; | |
let variantId = e.target.closest(".cart-item").dataset.productId; | |
let name = e.target | |
.closest(".cart-item") | |
.querySelector(".cart-item-title").innerHTML; | |
updateProductsQuantity(variantId, operation); | |
} else if (e.target.matches(".delete-cart-item")) { | |
let variantId = e.target.closest(".cart-item").dataset.productId; | |
deleteCartItem(variantId); | |
} else if (e.target.matches(".check-out")) { | |
createCheckoutLinkAndRedirect(); | |
document.querySelector(".cart-action-wrapper img").style.display = | |
"block"; | |
} else if (e.target.matches(".update-quantity")) { | |
console.log("updating"); | |
let input = e.target | |
.closest(".shopify-buy__quantity-container") | |
.querySelector("input"); | |
if (e.target.dataset.operation == "add") { | |
console.log((input.value = parseInt(input.value) + 1)); | |
} else if (e.target.dataset.operation == "subtract") { | |
if (parseInt(input.value) < 2) return; | |
console.log((input.value = parseInt(input.value) - 1)); | |
} | |
} | |
}); | |
if (localStorage.lineItems) { | |
console.log("localStorage.lineItems received"); | |
let lineItems = JSON.parse(localStorage.lineItems); | |
render(); | |
} | |
var productsJSON | |
// fetch all products from shopify | |
client.product.fetchAll().then((products) => { | |
renderProducts(products); | |
productsJSON = products | |
// console.log(products); | |
}); | |
// fetch only available products from shopify | |
client.product.fetchQuery({ first: 250, query: "available_for_sale:true" }).then((products) => { | |
renderProducts(products); | |
productsJSON = products | |
console.log(products); | |
}); | |
function renderProducts(products) { | |
const productsContainer = document.querySelector(".products"); | |
productsContainer.innerHTML = ""; | |
products.forEach((product) => { | |
// console.log(product) | |
productsContainer.innerHTML += ` | |
<div class="has-image shopify-buy__layout-vertical shopify-buy__product"> | |
<div | |
class="shopify-buy__product-img-wrapper" | |
data-element="product.imgWrapper" | |
> | |
<img | |
alt="${product.title}" | |
data-element="product.img" | |
class="shopify-buy__product__variant-img" | |
src="${product.images[0].src}" | |
/> | |
</div> | |
<a class="product-link" href="/shop/${product.handle}"> | |
<h1 class="shopify-buy__product__title" data-element="product.title"> | |
${product.title} | |
</h1> | |
</a> | |
<div class="shopify-buy__product__price" data-element="product.prices"> | |
<span | |
class="shopify-buy__product__actual-price" | |
data-element="product.price" | |
>$${product.variants[0].price}</span | |
> | |
</div> | |
<div | |
class="shopify-buy__btn-and-quantity" | |
data-element="product.buttonWithQuantity" | |
> | |
<div | |
class="shopify-buy__quantity-container" | |
data-element="product.quantity" | |
> | |
<div class="shopify-buy__quantity-btns"> | |
<button data-operation="add" class="update-quantity">+</button> | |
<button data-operation="subtract" class="update-quantity">-</button> | |
</div> | |
<input class="shopify-buy__quantity" | |
readonly | |
type="number" | |
min="0" | |
max="100 | |
aria-label="Quantity" | |
value="1" | |
data-element="product.quantityInput" | |
/> | |
</div> | |
<div | |
class="shopify-buy__btn-wrapper" | |
data-element="product.buttonWrapper" | |
> | |
<button | |
data-product-id="${product.variants[0].id}" | |
class="add-to-cart shopify-buy__btn shopify-buy__beside-quantity" | |
data-element="product.button" | |
> | |
ADD TO CART | |
</button> | |
</div> | |
</div> | |
</div> | |
`; | |
}); | |
} | |
document.querySelector(".products").addEventListener("click", (e) => { | |
if (!e.target.classList.contains("add-to-cart")) return; | |
const productId = e.target.dataset.productId; | |
const productQuantity = parseFloat( | |
e.target.closest('.shopify-buy__btn-and-quantity').querySelector('input').value!="" ? | |
e.target.closest('.shopify-buy__btn-and-quantity').querySelector('input').value : 1 | |
); | |
console.log(productQuantity); | |
const product = productsJSON.find((product) => product.variants[0].id == productId); | |
const productTitle = product.title , | |
productPrice = product.variants[0].price , | |
productImage = product.images[0].src; | |
let oldlineItems = localStorage.lineItems | |
? JSON.parse(localStorage.lineItems) | |
: []; | |
// add repeated products in combination | |
let lineItemsToAdd = [ | |
{ | |
variantId: productId, | |
quantity: productQuantity, | |
customAttributes: [{key: "title", value: productTitle},{key: "price", value: productPrice} , {key: "image", value: productImage}], | |
}, | |
]; | |
let combinedLineItems = | |
oldlineItems.length > 0 | |
? [...oldlineItems, ...lineItemsToAdd] | |
: lineItemsToAdd; | |
const reducedArr = combinedLineItems.reduce((acc, cur) => { | |
acc[cur.variantId] ? acc[cur.variantId].quantity += cur.quantity : acc[cur.variantId] = cur; | |
return acc; | |
}, {}); | |
combinedLineItems = Object.values(reducedArr); | |
addProducttoLocalStorage(combinedLineItems); | |
console.log(combinedLineItems); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment