Do you want a shopping cart built entirely in JavaScript? With session / storage everything! With no PHP or server-side code, then read on and rock on.
Earlier I have written a lot of PHP shopping cart code using server-side sessions. Now let us see a similar concept on the client-side to build a JavaScript shopping cart.
The Window.sessionStorage is the right solution to create a session-based shopping cart. It is free from PHP or other server-side code, unlike previous eCommerce examples.
The sessionStorage is one of the standard JavaScript concepts of WebStorage API. It is a client-side session object that tends to set, get and clear data with respect to it. This object’s persistence is based on the browser’s session availability.
The JavaScript shopping cart implementation is possible with sessionStorage like as below. The below table shows the mapping of sessionStorage capability with shopping cart features.
This section shows the execution flow of the JavaScript shopping cart code. It covers “add to cart” to check out and to the payment step.
In this tutorial, we will see steps 1 and 2 of a JavaScript shopping cart. You can integrate with the payment options coded with different articles. Example: Integrate PayPal checkout into the eCommerce website.
This example provides bare minimal features of a Javascript shopping cart. It supports performing the “add to cart” and “clear cart” functionalities via JavaScript.
This code also builds and supplies product gallery HTML from JavaScript.
It is a jQuery-based client-side implementation with the use of JavaScript sessionStorage.
This HTML code has placeholders to load UI for the following from JavaScript.
When this document is ready, a JavaScript code prepares HTML for the product grid.
In the product grid, it contains inputs to select a quantity and post to perform the “add to cart” operation.
The cart.js handles the client-side code to perform the shopping cart operations. It will be included in this template.
<div class="container">
<!-- Shopping cart table wrapper -->
<div id="shopping-cart">
<div class="txt-heading">
<h1>Shopping cart</h1>
</div>
<a onClick="emptyCart()" id="btnEmpty">Empty Cart</a>
<table class="tbl-cart" cellpadding="10" cellspacing="1">
<thead>
<tr>
<th>Name</th>
<th class='text-right' width="10%">Unit Price</th>
<th class='text-right' width="5%">Quantity</th>
<th class='text-right' width="10%">Sub Total</th>
</tr>
</thead>
<!-- Cart table to load data on "add to cart" action -->
<tbody id="cartTableBody">
</tbody>
<tfoot>
<tr>
<td class="text-right">Total:</td>
<td id="itemCount" class="text-right" colspan="2"></td>
<td id="totalAmount" class="text-right"></td>
</tr>
</tfoot>
</table>
</div>
<!-- Product gallery shell to load HTML from JavaScript code -->
<div id="product-grid">
<div class="txt-heading">
<h1>Products</h1>
</div>
<div id="product-item-container"></div>
</div>
</div>
This script performs the following.
The productItem
contains the product JSON data. It contains a row of product data with name, price and photo path.
The showProductGallery
method iterates this productItem
JSON and builds the product gallery HTML.
In this gallery, each product tile contains the option “add to cart”. It moves the selected product to the cart session by clicking the “Add to cart” button.
The JavaScript code uses for each loop to iterate theproductItem
JSON.
$(document).ready(function() {
var productItem = [{
productName: "FinePix Pro2 3D Camera",
price: "1800.00",
photo: "camera.jpg"
},
{
productName: "EXP Portable Hard Drive",
price: "800.00",
photo: "external-hard-drive.jpg"
},
{
productName: "Luxury Ultra thin Wrist Watch",
price: "500.00",
photo: "laptop.jpg"
},
{
productName: "XP 1155 Intel Core Laptop",
price: "1000.00",
photo: "watch.jpg"
}];
showProductGallery(productItem);
});
function showProductGallery(product) {
//Iterate javascript shopping cart array
var productHTML = "";
product.forEach(function(item) {
productHTML += '<div class="product-item">'+
'<img src="product-images/' + item.photo + '">'+
'<div class="productname">' + item.productName + '</div>'+
'<div class="price">$<span>' + item.price + '</span></div>'+
'<div class="cart-action">'+
'<input type="text" class="product-quantity" name="quantity" value="1" size="2" />'+
'<input type="submit" value="Add to Cart" class="add-to-cart" onClick="addToCart(this)" />'+
'</div>'+
'</div>';
"<tr>";
});
$('#product-item-container').html(productHTML);
}
This “add to cart” JavaScript handler is a core functionality of the example. This code initiates the JavaScript sessionStorage object.
On clicking the “Add to cart” button on the product tile, this function is invoked.
It reads the product details from the product grid where the clicked “Add to cart” is placed. For example, it gets the product name, quantity and other details.
Using these details, this code prepares the JSON instance of the cart item row. Then, it appends the newly added items to the existing cart sessionStorage object.
function addToCart(element) {
var productParent = $(element).closest('div.product-item');
var price = $(productParent).find('.price span').text();
var productName = $(productParent).find('.productname').text();
var quantity = $(productParent).find('.product-quantity').val();
var cartItem = {
productName: productName,
price: price,
quantity: quantity
};
var cartItemJSON = JSON.stringify(cartItem);
var cartArray = new Array();
// If javascript shopping cart session is not empty
if (sessionStorage.getItem('shopping-cart')) {
cartArray = JSON.parse(sessionStorage.getItem('shopping-cart'));
}
cartArray.push(cartItemJSON);
var cartJSON = JSON.stringify(cartArray);
sessionStorage.setItem('shopping-cart', cartJSON);
showCartTable();
}
This JavaScript shopping cart code contains an option to empty the cart table.
It explicitly clears the sessionStorage instance created to have the cart items.
At the end of both “Add to cart” and the “clear cart” actions, the cart table UI is rebuilt with the latest session data.
The showCartTable
function is called for updating the cart table UI and the total count.
function emptyCart() {
if (sessionStorage.getItem('shopping-cart')) {
// Clear JavaScript sessionStorage by index
sessionStorage.removeItem('shopping-cart');
showCartTable();
}
}
This code displays the logic of showCartTable()
to rebuild cart HTML and update UI.
It initiates variables to hold the following data. These are used in the JavaScript shopping cart code.
It checks cart sessionStorage and iterates the array if exists. During the iteration, it builds the cart table HTML and computes the total count and price.
The cart sessionStorage data is pushed to the UI via this JavaScript function. It reflects the latest cart state to the end-users.
function showCartTable() {
var cartRowHTML = "";
var itemCount = 0;
var grandTotal = 0;
var price = 0;
var quantity = 0;
var subTotal = 0;
if (sessionStorage.getItem('shopping-cart')) {
var shoppingCart = JSON.parse(sessionStorage.getItem('shopping-cart'));
itemCount = shoppingCart.length;
//Iterate javascript shopping cart array
shoppingCart.forEach(function(item) {
var cartItem = JSON.parse(item);
price = parseFloat(cartItem.price);
quantity = parseInt(cartItem.quantity);
subTotal = price * quantity
cartRowHTML += "<tr>" +
"<td>" + cartItem.productName + "</td>" +
"<td class='text-right'>$" + price.toFixed(2) + "</td>" +
"<td class='text-right'>" + quantity + "</td>" +
"<td class='text-right'>$" + subTotal.toFixed(2) + "</td>" +
"</tr>";
grandTotal += subTotal;
});
}
$('#cartTableBody').html(cartRowHTML);
$('#itemCount').text(itemCount);
$('#totalAmount').text("$" + grandTotal.toFixed(2));
}
The output will be familiar to whom already have seen my older shopping cart code created in PHP.
It is designed as a single-page shopping cart solution. It shows both the gallery and cart on the same page.
The WebStorage API’s sessionStorage will be expired when the browser is closed. This API provides one more storage object which is localStorage.
The localStorage object is similar to sessionStorage. The only difference is that the localStorage keeps data until explicit action.
So, this concept helps to have a persistent cart. That is to retain the customers’ cart items even if they closed the browser.
The source code uses sessionStorage for this JavaScript shopping cart code. Include the following file instead of cart.js if you want to use the localStorage object.
cart-local-storage.js
$(document).ready(function() {
var productItem = [{
productName: "FinePix Pro2 3D Camera",
price: "1800.00",
photo: "camera.jpg"
},
{
productName: "EXP Portable Hard Drive",
price: "800.00",
photo: "external-hard-drive.jpg"
},
{
productName: "Luxury Ultra thin Wrist Watch",
price: "500.00",
photo: "laptop.jpg"
},
{
productName: "XP 1155 Intel Core Laptop",
price: "1000.00",
photo: "watch.jpg"
}];
showProductGallery(productItem);
showCartTable();
});
function addToCart(element) {
var productParent = $(element).closest('div.product-item');
var price = $(productParent).find('.price span').text();
var productName = $(productParent).find('.productname').text();
var quantity = $(productParent).find('.product-quantity').val();
var cartItem = {
productName: productName,
price: price,
quantity: quantity
};
var cartItemJSON = JSON.stringify(cartItem);
var cartArray = new Array();
// If javascript shopping cart session is not empty
if (localStorage.getItem('shopping-cart')) {
cartArray = JSON.parse(localStorage.getItem('shopping-cart'));
}
cartArray.push(cartItemJSON);
var cartJSON = JSON.stringify(cartArray);
localStorage.setItem('shopping-cart', cartJSON);
showCartTable();
}
function emptyCart() {
if (localStorage.getItem('shopping-cart')) {
// Clear JavaScript localStorage by index
localStorage.removeItem('shopping-cart');
showCartTable();
}
}
function removeCartItem(index) {
if (localStorage.getItem('shopping-cart')) {
var shoppingCart = JSON.parse(localStorage.getItem('shopping-cart'));
localStorage.removeItem(shoppingCart[index]);
showCartTable();
}
}
function showCartTable() {
var cartRowHTML = "";
var itemCount = 0;
var grandTotal = 0;
var price = 0;
var quantity = 0;
var subTotal = 0;
if (localStorage.getItem('shopping-cart')) {
var shoppingCart = JSON.parse(localStorage.getItem('shopping-cart'));
itemCount = shoppingCart.length;
//Iterate javascript shopping cart array
shoppingCart.forEach(function(item) {
var cartItem = JSON.parse(item);
price = parseFloat(cartItem.price);
quantity = parseInt(cartItem.quantity);
subTotal = price * quantity
cartRowHTML += "<tr>" +
"<td>" + cartItem.productName + "</td>" +
"<td class='text-right'>$" + price.toFixed(2) + "</td>" +
"<td class='text-right'>" + quantity + "</td>" +
"<td class='text-right'>$" + subTotal.toFixed(2) + "</td>" +
"</tr>";
grandTotal += subTotal;
});
}
$('#cartTableBody').html(cartRowHTML);
$('#itemCount').text(itemCount);
$('#totalAmount').text("$" + grandTotal.toFixed(2));
}
function showProductGallery(product) {
//Iterate javascript shopping cart array
var productHTML = "";
product.forEach(function(item) {
productHTML += '<div class="product-item">'+
'<img src="product-images/' + item.photo + '">'+
'<div class="productname">' + item.productName + '</div>'+
'<div class="price">$<span>' + item.price + '</span></div>'+
'<div class="cart-action">'+
'<input type="text" class="product-quantity" name="quantity" value="1" size="2" />'+
'<input type="submit" value="Add to Cart" class="add-to-cart" onClick="addToCart(this)" />'+
'</div>'+
'</div>';
"<tr>";
});
$('#product-item-container').html(productHTML);
}
Until the “add to cart” step, the client-side handling is fine. When proceeding with checkout, it is preferable to use server-side middleware.
It is for safety purposes to handle security loopholes. It will do the sanitization, validation of data authenticity and more verification process.
So, we have created a JavaScript shopping cart code using the sessionStorage object. And also, we saw one more option to add the cart item persistency with the localStorage object.
The client-side shopping cart implementation is not a complete solution. But, it has the advantages of minimalism. It will suit the thin static cart available online.
It is suitable for the shops having client-side integrations connected with hosted services.
Download