let cart = {};
$.getJSON('goods.json', function(data) {
let goods = data;
checkCart();
//console.log(cart);
showCart();
saveCartToLocalStorage();
function showCart() {
if ($.isEmptyObject(cart)) {
let out = '<p class="empty-cart">Sorry! <br>But your cart is empty!<br>Go to our store page and select a product <br> <a href="shop.html">Our store</a></p>';
$('#my-cart').html(out);
} else {
var out = '';
for (let key in cart) {
out += '<div class="cart-goods">';
out += '<ul>';
out += '<li>';
out += '<button class="delete" data-art="' + key + '">x</button>';
out += '<img src="' + goods[key].image + '">';
out += '<p>' + goods[key].name + '</p>';
out += '<span class="quantity">Quantity:</span> ' + '<button class="less" data-art="' + key + '"> - </button>';
out += cart[key];
out += '<button class="more" data-art="' + key + '"> + </button>';
out += '<br><span class="cost">Cost:</span> ' + cart[key] * goods[key].price + ' $';
out += '<br>';
out += '<hr>';
out += '</li>';
out += '</ul>';
out += '</div>';
}
}
$('#my-cart').html(out);
$('.more').on('click', moreGoods);
$('.less').on('click', lessGoods);
$('.delete').on('click', deleteGoods);
}
function moreGoods() {
let artical = $(this).attr('data-art');
cart[artical]++;
saveCartToLocalStorage();
showCart();
}
function lessGoods() {
let artical = $(this).attr('data-art');
if (cart[artical] > 1) {
cart[artical]--;
} else {
delete cart[artical];
}
saveCartToLocalStorage();
showCart();
}
function deleteGoods() {
let artical = $(this).attr('data-art');
delete cart[artical];
saveCartToLocalStorage();
showCart();
}
});
function checkCart() {
if (localStorage.getItem('cart') != null) {
cart = JSON.parse(localStorage.getItem('cart'));
}
}
function saveCartToLocalStorage() {
localStorage.setItem('cart', JSON.stringify(cart));
}