Skip to content

Instantly share code, notes, and snippets.

@umutyerebakmaz
Last active June 16, 2022 21:16
Show Gist options
  • Save umutyerebakmaz/5e0a7bb440753b4f72bbd9e9ba0f58f8 to your computer and use it in GitHub Desktop.
Save umutyerebakmaz/5e0a7bb440753b4f72bbd9e9ba0f58f8 to your computer and use it in GitHub Desktop.
JavaScript Shoping Cart Example Full Featured
// variables
const cartBtn = document.querySelector(".cart-btn");
const closeCartBtn = document.querySelector(".close-cart");
const clearCartBtn = document.querySelector(".clear-cart");
const cartDOM = document.querySelector(".cart");
const cartOverlay = document.querySelector(".cart-overlay");
const cartItems = document.querySelector(".cart-items");
const cartTotal = document.querySelector(".cart-total"); // cart totals
const cartContent = document.querySelector(".cart-content");
// const productsDOM = document.querySelector(".products-center");
let cart = [];
let buttonsDOM = [];
// tamam
class Products {
async getProducts() {
try {
let result = await fetch('products');
return await result.json();
}
catch (error) {
console.log(error);
}
}
}
// tamam
class UI {
getBagButtons() {
let buttons = [...document.querySelectorAll(".bag-btn")];
buttonsDOM = buttons;
buttons.forEach(button => {
let id = parseInt(button.dataset.id);
let inCart = cart.find(item => item.id === id);
if (inCart) {
button.innerText = "In Cart";
button.disabled = true;
}
button.addEventListener("click", event => {
// disable button
event.target.innerText = "In Cart";
event.target.disabled = true;
// add to cart
let cartItem = { ...Storage.getProduct(id), amount: 1 };
cart = [...cart, cartItem];
Storage.saveCart(cart);
// add to DOM
this.setCartValues(cart);
this.addCartItem(cartItem);
// this.showCart();
});
});
}
setCartValues(cart) {
let tempTotal = 0;
let itemsTotal = 0;
cart.map(item => {
tempTotal += item.price * item.amount;
itemsTotal += item.amount;
});
cartTotal.innerText = parseFloat(tempTotal.toFixed(2));
cartItems.innerText = itemsTotal;
}
addCartItem(item) {
const div = document.createElement("div");
div.classList.add("cart-item");
div.innerHTML = `
<img src="/img/doner.jpg" alt="${item.title}">
<div class="cart-item-info">
<h4>${item.title}</h4>
<h5>$${item.price}</h5>
<span class="remove-item" data-id="${item.id}">remove</span>
</div>
<div class="chevrons">
<i class="fas fa-chevron-up" data-id=${item.id}></i>
<span class="item-amount">${item.amount}</span>
<i class="fas fa-chevron-down" data-id=${item.id}></i>
</div>
`;
cartContent.appendChild(div);
}
showCart() {
cartOverlay.classList.add("transparentBcg");
cartDOM.classList.add("showCart");
}
hideCart() {
cartOverlay.classList.remove("transparentBcg");
cartDOM.classList.remove("showCart");
}
setupAPP() {
cart = Storage.getCart();
this.setCartValues(cart);
this.populateCart(cart);
cartBtn.addEventListener("click", this.showCart);
closeCartBtn.addEventListener("click", this.hideCart);
}
populateCart(cart) {
cart.forEach(item => this.addCartItem(item));
}
cartLogic() {
clearCartBtn.addEventListener("click", () => {
this.clearCart();
});
cartContent.addEventListener("click", event => {
if (event.target.classList.contains("remove-item")) {
let removeItem = event.target;
let id = parseInt(removeItem.dataset.id);
console.log(id);
cartContent.removeChild(removeItem.parentElement.parentElement);
// remove item
this.removeItem(id);
} else if (event.target.classList.contains("fa-chevron-up")) {
let addAmount = event.target;
let id = parseInt(addAmount.dataset.id);
let tempItem = cart.find(item => item.id === id);
tempItem.amount = tempItem.amount + 1;
Storage.saveCart(cart);
this.setCartValues(cart);
addAmount.nextElementSibling.innerText = tempItem.amount;
} else if (event.target.classList.contains("fa-chevron-down")) {
let lowerAmount = event.target;
let id = parseInt(lowerAmount.dataset.id);
let tempItem = cart.find(item => item.id === id);
tempItem.amount = tempItem.amount - 1;
if (tempItem.amount > 0) {
Storage.saveCart(cart);
this.setCartValues(cart);
lowerAmount.previousElementSibling.innerText = tempItem.amount;
} else {
cartContent.removeChild(lowerAmount.parentElement.parentElement);
this.removeItem(id);
}
}
});
}
clearCart() {
let cartItems = cart.map(item => item.id);
cartItems.forEach(id => this.removeItem(id));
while (cartContent.children.length > 0) {
cartContent.removeChild(cartContent.children[0]);
}
this.hideCart();
}
removeItem(id) {
cart = cart.filter(item => item.id !== parseInt(id));
this.setCartValues(cart);
Storage.saveCart(cart);
let button = this.getSingleButton(id);
button.disabled = false;
button.innerHTML = `<i class="fas fa-shopping-cart"></i>add to bag`;
}
getSingleButton(id) {
return buttonsDOM.find(button => parseInt(button.dataset.id) === id);
}
}
// tamam
class Storage {
static saveProducts(products) {
localStorage.setItem("products", JSON.stringify(products));
}
static getProduct(id) {
let products = JSON.parse(localStorage.getItem("products"));
return products.find(product => product.id === id);
}
static saveCart(cart) {
localStorage.setItem("cart", JSON.stringify(cart));
}
static getCart() {
return localStorage.getItem("cart")
? JSON.parse(localStorage.getItem("cart"))
: [];
}
}
// tamam
document.addEventListener("DOMContentLoaded", () => {
const ui = new UI();
const products = new Products();
ui.setupAPP();
// get all products
products
.getProducts()
.then(products => {
// ui.displayProducts(products);
Storage.saveProducts(products);
})
.then(() => {
ui.getBagButtons();
ui.cartLogic();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment