Shopping Cart Experiment
by Emily Humphrey
HTML
<div class="cart-ctn"><span class="cart"></span> | <button class="JS-view">View</button></div>
<div class="products">
<div class="product">
<h1>Product 1</h1>
<button data-prod-id="100" data-prod-name="Product 1" data-prod-price="25">Add to Cart</button>
</div>
<div class="product">
<h1>Product 2</h1>
<button data-prod-id="200" data-prod-name="Product 2" data-prod-price="50">Add to Cart</button>
</div>
<div class="product">
<h1>Product 3</h1>
<button data-prod-id="300" data-prod-name="Product 3" data-prod-price="75">Add to Cart</button>
</div>
<div class="product">
<h1>Product 4</h1>
<button data-prod-id="400" data-prod-name="Product 4" data-prod-price="100">Add to Cart</button>
</div>
</div>
<div class="view-cart"></div>
CSS
body{
font-family: sans-serif;
margin: 0;
padding: 20px;
}
h1{
font-size: 20px;
}
button{
cursor: pointer;
padding: 5px 10px;
background: #eee;
border: 1px solid #ccc;
outline: none;
}
.cart-ctn{
padding: 0 0 10px;
border-bottom: 1px solid #ccc;
margin: 0 0 20px;
font-size: 12px;
text-align: right;
}
.products{
display: flex;
margin: 0 auto;
}
.product{
display: block;
width: 25%;
text-align: center;
}
table{
width: 100%;
padding: 10px;
}
table > tr{
padding-bottom: 10px;
}
td{
text-align: center;
}
JavaScript
var cart = [];
updateCart();
$(".product > button").on("click", function(){
var id = $(this).attr("data-prod-id");
var alreadyInCart = false;
for(var i = 0; i < cart.length; i++){
if(cart[i].id === id){
alreadyInCart = true;
cart[i].qty = cart[i].qty + 1;
}
}
if(alreadyInCart === false){
addToCart(
$(this).attr("data-prod-id"),
$(this).attr("data-prod-name"),
$(this).attr("data-prod-price"),
1
);
}
updateCart();
console.log(cart);
});
$(".JS-view").on("click", function(){
listCart()
});
function listCart(){
var table = $("<table>"+"</table>");
$(".view-cart").html(table);
table.html(
"<tr>"+
"<td>Product</td>"+
"<td>Price</td>"+
"<td>QTY</td>"+
"<td>Total</td>"+
"</tr>"
);
for(var i = 0; i < cart.length; i++){
table.append(
"<tr>"+
"<td>"+cart[i].name+"</td>"+
"<td>"+cart[i].price+"</td>"+
"<td>"+cart[i].qty+"</td>"+
"<td>"+(cart[i].price*cart[i].qty)+"</td>"+
"</tr>"
);
}
}
function addToCart(itemID,itemName,itemPrice,qty){
cart.push({name: itemName, price: itemPrice, id: itemID, qty: 1});
}
function updateCart(){
var cartItems = 0;
var cartTotal = 0;
for(var i = 0; i < cart.length; i++){
var price = parseInt(cart[i].price) * parseInt(cart[i].qty);
var items = parseInt(cart[i].qty);
cartItems = cartItems + items;
cartTotal = cartTotal + price;
}
if(cartItems === 0){
return updateMessage("Cart is empty");
} else if(cartItems === 1){
return updateMessage("Cart: 1 item - $"+cartTotal.toFixed(2));
} else{
return updateMessage("Cart: "+cartItems+" items - $"+cartTotal.toFixed(2));
}
function updateMessage(message){
var cartCtn = $(".cart");
...