Create JavaScript Shopping Cart with Add to Cart Code

by Vincy. Last modified on June 21st, 2022.

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.

What is sessionStorage?

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.

How to build a JavaScript shopping cart using sessionStorage?

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.

  • setItem() – Add to cart from the shopping gallery by referring to the purchased product id. It also is used to edit a cart item by replacing the value array.
  • getItem() – Read and display the cart items by iterating the sessionStorage object array.
  • removeItem() – Remove a single item from the cart by specifying the item index.
  • clear() – Empty the cart by unsetting the sessionStorage instance.

Shopping cart – checkout – payment

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.

  • Step 1: On “add to cart” action the sessionStorage object builds the purchased item array.
  • Step 2: Then, it gets the buyer’s payment details on a checkout form.
  • Step 3: Can renders payment options like PayPal with the request parameter array. This array contains purchased items and the buyer’s payment details.
  • Step 4: An alternate to step 3, that is, an email checkout. This suits the shopping cart not dealing with instant payment on the flow.

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.

JavaScript shopping cart example

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.

HTML code to display shopping cart UI

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>

Client-side code to perform JavaScript shopping cart actions

This script performs the following.

  1. Load product gallery from JSON data.
  2. “Add to cart” action to move a product into the cart table.
  3. Load and change the shopping cart status on each cart action.
  4. Update total cart items and total price on each change.
  5. Empty the cart by clearing the session.

Load product gallery from JSON data

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);
}

“Add to cart” action to move a product into the cart table

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();
}

Empty the cart by clearing the session

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();
	}
}

Load cart row, item count, the total amount from sessionStorage object

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.

  • Cart table HTML.
  • A total number of items added to the cart.
  • A total amount of the purchased cart items.

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));
}

JavaScript shopping cart output screenshot

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.

javascript shopping cart output

Persistent JavaScript shopping cart with localStorage instance

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);
}

Security caution

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.

Conclusion

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

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this Article