var cart = []; $(function () { showCart(); if (localStorage.cart) { cart = JSON.parse(localStorage.cart); showCart(); } $(document).on('click', '.add-to-cart', function (e) { e.preventDefault(); var id = $(this).attr('data-id'); var price = $(this).attr('data-price'); var tax = $(this).attr('data-tax'); var name = $(this).attr('data-name'); var photo = $(this).attr('data-img'); var color = $(this).attr('data-color'); var category = $(this).attr('data-category'); var status = $(this).attr('data-status'); addToCart(id, name, price, tax, photo, color, category, status); }); }); var qty = 0; function addToCart(id, name, price, tax, photo, color, category, status, qty = 1) { // update qty if product is already present for (var i in cart) { if (cart[i].id == id) { cart[i].qty += qty; showCart(); saveCart(); return; } } // create JavaScript Object var item = { id: id, name: name, price: price, tax: tax, photo: photo, color: color, qty: qty, category: category, status: status }; cart.push(item); saveCart(); $('html, body').animate({ scrollTop: $(".cart-info").offset().top - 20 }, 'slow'); showCart(); } function deleteItem(index) { cart.splice(index, 1); // delete item at index showCart(); saveCart(); } function saveCart() { if (window.localStorage) { localStorage.cart = JSON.stringify(cart); } } function showCart() { if (cart.length === 0) { $(".cart-total").text(0); return; } var totalItem = cart.length; $(".cart-total").text(totalItem); }