How To Build Your Own Shopping Cart in Javascript?


(Arrowsoft.IT Srls) #1

Hi There!

In this post, We will explore how to implement a cart object with Javascript and jQuery. Maybe, this is one of the most important object on the web, because all e-commerce sites use the cart for mantain the list of articles that the customer want to buy.
Think for a while about how many money are handled by this object. :astonished:

As a developer, you must know how the cart work and how to write code to have a working class to drive in order to handle some basic function like addProductInCart, removeProductFromCart, getCartValue and finally getItemNum.

Why we need to know how cart can be implemented?

We think that this question is the core of our article. If you need to setting up an e-commerce website or a MarketPlace for a Customer, you could use one of the CMS that exists on the web: Magento, OsCommerce, Woocommerce and others works fine! But, this CMS limite your creativity to their programmers choices.
What will happen if your customer want a non standard e-commerce system? :disappointed:
Can the CMS cover all the strange request of the customer?
Somethime the answer is… NO!:point_up:

Then, sometime you must start from scratch!

##Basic Requirements
The primary goal of a cart is to store a list of item that the costumer could buy. Then, we can imagine the cart object like a list of unique object, each of them identified by unique id.
For each item, the costumer choose how many of it want to buy, then each item identified by unique id have a quantity property in which is stored the quantity of product to buy. Also, each item have it own price.

We can write a list of the requirements related to our cart:

  1. Must provide method to add, update and remove item
  2. Must store the item list accross the session; if user close browser, when he return to website cart should be there!
  3. Must provide method to be used for calculate total amount and item number


We start from the requirement 2. We need to store cart in rhe browser memory avoiding all the problems that in the past we has with SESSION scope variables.
We can use localStorage feature! We will mantain a copy of the cart object in the localStorage object in order to have all the data in local and not on the server side! But, in which manner we can do this thing?

We just need two simple functions that we named getLocalData and setLocalData.

function getLocalData(name)
	return localStorage.getItem(name)
function setLocalData(name,value)
	if (value!=null)

Fine! Now we can store and read from the browser memory. Obviously, take into account that a page can accesa only to the data that it save. You are not able to read localStorage of other page!

Encode the cart object

Now, we need to implement the points 1 and 2. For first we need a space in which we can save the item. We love simple thing so we will use javascript Array. But, in which manner we can store an array in the localStorage, if the localStorage accept only strings?
The answer is JSON!
Javascript have native support for marshalling and unmarshalling in json format, so if we use javascript we can save all thing without problem (yes the image can be convertes feom binarymto base64 that is string format).

Array and inizializator

We will start by declaring the variables, one for the array and one for the array item counter and one function that must be called every time a new page that use cart is loaded.

var cartObj = null; // global pointer to cart
var cartCI = -1;

function cart_initCart() 
	cartObj = new Array();
	cartCI = 0;
	// Check in browser memory if there are a saved cart
	if (getLocalData("NETSELL5_USERCART")!=null)
    // if previoys cart is present load it
		cartCI = getLocalData("NETSELL5_USERCART_CI");
		cartObj = JSON.parse(getLocalData("NETSELL5_USERCART"));
		console.log("\t[CART-v2] Cart is empty!");

Fantastic! We have a space in which we can add, update and remove item! Now we need method to do this actions.

:raised_hand::raised_hand:Be careful here!:raised_hand::raised_hand::fire: Cart_initCart must be called when the webpage is ready* because we need to restore cart from the memory! This action is critical because javascript lose variables if current page change!

You can do this by attach and handler to body onready handler!

$(window).ready (function () { cart_initCart (); });

Add new item in cart

The following function handle the insertion of new row in the cart. We will describe the code by comment in the following code. Please note that you are free to store other data and not only parameters that we use for this article.

function addItemInCart(code,abfor,rifaf,dsart,qtord,prntve,vatval)
    // qtord is quantity to order
    // code is the sku or other code
   //abfor is the brand
   // rifaf is the brand code
   // prntve is the unitary price
   //vatval is the percentage fee 

  // if qtord is not numeric method fail
	if (!($.isNumeric(qtord)))
		 return false; 
    	qtord = parseFloat(qtord);
	if (!(qtord > 0)) {
	    alert('insert positive value');
	    return -1;
	// make new row
	var newRow = new Object();
	newRow["CDART"] = code;
	newRow["ABFOR"] = abfor;
	newRow["RIFAF"] = rifaf;
	newRow["DSART"] = dsart;

	newRow["QTORD"] = qtord;
	newRow["QTMNV"] = qtmnv;
	newRow["PRNTVE"] = prntve;
	newRow["ALIVA"] = VatVAL;

   // add new item to cart
	cartObj[cartCI++] = newRow;
   //save cart in localStorage


Get the number of

This function explains itself :laughing:

function cart_getItemsNum_v2() {
	var itemInCart = 0;
	for (var xr in cartObj)
	     // i need index of element in this routine so i didn't used OF in iteration
   	    r = cartObj[xr];
	    if (r==null) continue; // Removed ROW - ignore it
	return itemInCart;

Get the cart value (with and without vat)

This function compute the total amount of the cart with and without VAT charges.

function cart_getValue_v2() {

	var useVAT = true; 

	var kvalueVLMERE=0.0; // without vat
	var kvalueVLMERE_I = 0.0; // with vat
	var kvalueALIVA_VAL = 0.0; // vat chargea

	for (var r of cartObj) // iterate all the item
	    if (r==null) continue; // Removed ROW - ignore it

	    var prntve = parseFloat(r["PRNTVE"]);
	    var aliva = parseFloat(r["ALIVA"]);
	    var qtord = parseFloat(r["QTORD"]);

	    var totRowWithVAT = (prntve + ((prntve*aliva)/100))*qtord;
	    var totRowNOVAT = prntve*qtord;
	    var totRowALIVA = ((prntve*aliva)/100)*qtord; 

	    kvalueVLMERE = kvalueVLMERE + totRowNOVAT;
	    kvalueVLMERE_I = kvalueVLMERE_I + totRowWithVAT; 
	    kvalueALIVA_VAL = kvalueALIVA_VAL + totRowALIVA;


	var cartValueObj = new Object();
	cartValueObj["VLMERE"] = kvalueVLMERE;
	cartValueObj["VLMERE_I"] = kvalueVLMERE_I;
	cartValueObj["ALIVA_VAL"] = kvalueALIVA_VAL;

	return cartValueObj;


Remove and item from cart

function cart_removeCartRow_v2(rowid)
	cartObj[rowid]=null; // sign row as invalid

Update an item in cart

function cart_updateQtordInRow_v2(rowIndex,newQtord)
   // like add item this function fail if qtord is not valid
	if (!($.isNumeric(newQtord)))
		 return false; 
    	newQtord = parseFloat(newQtord);
	if (!(newQtord > 0)) {
             alert('insert positive value' );
	    return -1;
  // update cart
	    cartObj[rowIndex]["QTORD"] = newQtord;
	 // update memory

Cart is ready to work

At this point the three requirements are satisfied. You can copy and paste the code in a blank html page in order to use your new cart object. Do not forget to add reference to jQuery! :laughing: