How we can create a shopping cart program which stores data locally on the device? Solution: See this JavaScript Shopping Cart with Localstorage Function, Local Storage Shopping App.
Previously I have shared some shopping cart related programs, but this is a shopping cart program that stores data locally. Basically, a localstorage program stores data and values locally on your device, like a server. The main difference of simple JS program and local store based program is when you refresh the page all values will reset in the normal program, but the localstorage program‘s data will safe and the same as previously.
Today you will learn to create Local Storage Shopping App using JavaScript. Basically, there are 3 products with image and title, quantity box, add to cart button in the main view. On the left side, the cart section placed, where you can see selected or added items, price, selected quantity, checkout button, and clear cart button. At the top there is navbar for with title, also there are some other titles like for product list and cart. You can select a quantity and add the product to the cart, also you can clear the cart.
So, Today I am sharing JavaScript Shopping Cart with Localstorage Function. There I have used a CSS library and some custom CSS for styling and the whole functions are based on JavaScript. I have used the jQuery library to creating the program, as we know jQuery is a JS library that’s why I am calling this a JavaScript program. Also, there used JSON and ajax commands which are powered by jQuery file.
If you are thinking now how this shopping cart program actually is, then see the preview given below.
Preview Of Local Storage Shopping Cart App
See this video preview to getting an idea of how this cart looks like.
Now you can see this visually, also you can see it live by pressing the button given above. If you like this, then get the source code of its.
You May Also Like:
JavaScript Shopping Cart with Localstorage Source Code
Before sharing source code, let’s talk about it. First I have created a main div named row, and placed a navbar at top, and two sections for cart and product list. The layout is based on a CSS library called Foundation, and I have placed class and ID names according to the library’s pre-built command. Also in the HTML file, I have put some JS codes using <script> code for show and update cart. And all the external files like CSS, JS, jQuery, and other CDN files in the HTML file.
The program is based on a CSS library, that’s why there are less custom CSS codes. With CSS I have done only a few things like a shadow to box, gave background color to buttons, hover effect, and some other things. Other CSS values are based on the library’s CSS file. And now all things handling the JS file.
JS file creating there a local storage and stores values, and also handling other features like add to cart and clear cart. I have used some JSON and ajax call to store and pass data in local storage. There I have used localStorage.setItem command to store data locally. Also, I have used JS if{} else{} statement to create the program.
Left all other things you will understand after getting the codes, I can’t explain all in writing. For creating this program you have to create 3 files. First file for HTML, second file for CSS, and the third file for JavaScript. Follow the steps to creating this without any error.
index.html
Create an HTML file named ‘index.html‘ and put these codes given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
<!DOCTYPE html> <!-- Code By Webdevtrick ( https://webdevtrick.com ) --> <html lang="en" > <head> <meta charset="UTF-8"> <title>JS Shopping Cart | Webdevtrick.com</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css"> <link rel='stylesheet' href='https://cdn.jsdelivr.net/foundation/5.0.2/css/foundation.css'> <link rel="stylesheet" href="style.css"> </head> <body> <div class="row"> <nav class="top-bar" data-topbar> <ul class="title-area"> <li class="name"> <h1><a href="#">JS Shopping Cart</a></h1> </li> </ul> </nav> <div class="medium-4 columns"> <div class="cart"> <h1>Cart items</h1> <div class="row"> <div class="medium-6 columns"> <button class="tiny secondary" id="clear">Clear the cart</button> </div> <div class="medium-6 columns"> <button class="tiny disabled" title="Work in progress">Checkout</button> </div> </div> <div id="cartItems">Loading cart...</div> Total price: <strong id="totalPrice">0 $</strong> </div> </div> <div class="medium-8 columns"> <h1>Products List</h1> <div class="products"> <div class="product medium-4 columns" data-name="Vivobook" data-price="50000" data-id="0"> <img src="https://webdevtrick.com/wp-content/uploads/vivobook.jpg" alt="" /> <h3>Vivobook</h3> <input type="number" class="count" value="1" /> <button class="tiny">Add to cart</button> </div> <div class="product medium-4 columns" data-name="Surface Pro" data-price="85000" data-id="1"> <img src="https://webdevtrick.com/wp-content/uploads/surface.jpg" alt="" /> <h3>Surface Pro</h3> <input type="number" class="count" value="1" /> <button class="tiny">Add to cart</button> </div> <div class="product medium-4 columns" data-name="Predator" data-price="250000" data-id="2"> <img src="https://webdevtrick.com/wp-content/uploads/predator.jpg" alt="" /> <h3>Predator</h3> <input type="number" class="count" value="1" /> <button class="tiny">Add to cart</button> </div> </div> </div> </div> <script type="text/template" id="cartT"> <% _.each(items, function (item) { %> <div class = "panel"> <h3> <%= item.name %> </h3> <span class="label"> <%= item.count %> piece<% if(item.count > 1) {%>s <%}%> for <%= item.total %>₹</span > </div> <% }); %> </script> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js'></script> <script src="function.js"></script> </body> </html> |
style.css
Now create a CSS file named ‘style.css‘ and put these codes given here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/* Code By Webdevtrick ( https://webdevtrick.com ) */ nav { margin-bottom: 1em !important; } h1 { color: #ff6d34; } .cart { box-shadow: 0 0 5px #DDD; padding: 20px; } .tiny { background-color: #ff6d34; } #clear:hover { background-color: #ff6d34; color: #fff; } |
function.js
The final step, create a JavaScript file named ‘function.js‘ and put the codes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 |
// Code By Webdevtrick ( https://webdevtrick.com ) var cartId = "cart"; var localAdapter = { saveCart: function (object) { var stringified = JSON.stringify(object); localStorage.setItem(cartId, stringified); return true; }, getCart: function () { return JSON.parse(localStorage.getItem(cartId)); }, clearCart: function () { localStorage.removeItem(cartId); } }; var ajaxAdapter = { saveCart: function (object) { var stringified = JSON.stringify(object); // do an ajax request here }, getCart: function () { // do an ajax request -- recognize user by cookie / ip / session return JSON.parse(data); }, clearCart: function () { //do an ajax request here } }; var storage = localAdapter; var helpers = { getHtml: function (id) { return document.getElementById(id).innerHTML; }, setHtml: function (id, html) { document.getElementById(id).innerHTML = html; return true; }, itemData: function (object) { var count = object.querySelector(".count"), patt = new RegExp("^[1-9]([0-9]+)?$"); count.value = (patt.test(count.value) === true) ? parseInt(count.value) : 1; var item = { name: object.getAttribute('data-name'), price: object.getAttribute('data-price'), id: object.getAttribute('data-id'), count: count.value, total: parseInt(object.getAttribute('data-price')) * parseInt(count.value) }; return item; }, updateView: function () { var items = cart.getItems(), template = this.getHtml('cartT'), compiled = _.template(template, { items: items }); this.setHtml('cartItems', compiled); this.updateTotal(); }, emptyView: function () { this.setHtml('cartItems', '<p>Add some items to see</p>'); this.updateTotal(); }, updateTotal: function () { this.setHtml('totalPrice', cart.total + '₹'); } }; var cart = { count: 0, total: 0, items: [], getItems: function () { return this.items; }, setItems: function (items) { this.items = items; for (var i = 0; i < this.items.length; i++) { var _item = this.items[i]; this.total += _item.total; } }, clearItems: function () { this.items = []; this.total = 0; storage.clearCart(); helpers.emptyView(); }, addItem: function (item) { if (this.containsItem(item.id) === false) { this.items.push({ id: item.id, name: item.name, price: item.price, count: item.count, total: item.price * item.count }); storage.saveCart(this.items); } else { this.updateItem(item); } this.total += item.price * item.count; this.count += item.count; helpers.updateView(); }, containsItem: function (id) { if (this.items === undefined) { return false; } for (var i = 0; i < this.items.length; i++) { var _item = this.items[i]; if (id == _item.id) { return true; } } return false; }, updateItem: function (object) { for (var i = 0; i < this.items.length; i++) { var _item = this.items[i]; if (object.id === _item.id) { _item.count = parseInt(object.count) + parseInt(_item.count); _item.total = parseInt(object.total) + parseInt(_item.total); this.items[i] = _item; storage.saveCart(this.items); } } } }; document.addEventListener('DOMContentLoaded', function () { if (storage.getCart()) { cart.setItems(storage.getCart()); helpers.updateView(); } else { helpers.emptyView(); } var products = document.querySelectorAll('.product button'); [].forEach.call(products, function (product) { product.addEventListener('click', function (e) { var item = helpers.itemData(this.parentNode); cart.addItem(item); }); }); document.querySelector('#clear').addEventListener('click', function (e) { cart.clearItems(); }); }); |
That’s It. Now you have successfully created JavaScript Shopping Cart with Localstorage Function, Local Storage Shopping App. If you have any doubt or question comment down below.
Thanks For Visiting, Keep Visiting.
When you expect the checkout is completed? I am looking for this code for small carts with few products.
I was trying to show the cart total value in the panel to an modal…..Can you please guide me on this
Hi shaan,
Why My localstorage in browser is reseting when refreshing the page?
check ForEach statement well it might have a problem
hello,
wonderful work.
Can you help create a delete icon pour each product separately instead of clear cart ?
thank you