
A small (~3kb minified) shopping cart component that uses HTML5 local storage to remember the cart items (products) the users added to the cart.
Also provides a functionality to calculate the total price of selected products in the shopping cart.
How to use it:
1. Install & download the package and load the JavaScript file from the dist folder or from a CDN:
# Yarn $ yarn add cart-localstorage # NPM $ npm install cart-localstorage --save
<script src="./dist/cart-localstorage.min.js" defer></script> <!-- OR --> <script src="https://unpkg.com/cart-localstorage@latest/dist/cart-localstorage.min.js" defer></script>
2. Create an HTML table for the shopping cart.
<table class="table">
<tbody class="cart">
</tbody>
<tfoot>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td class="text-right">Total: <strong class="total"></strong></td>
<td></td>
</tfoot>
</table>3. The JavaScript to render the shopping cart.
function renderCart(items) {
const $cart = document.querySelector(".cart")
const $total = document.querySelector(".total")
$cart.innerHTML = items.map((item) => `
<tr>
<td>#${item.id}</td>
<td>${item.name}</td>
<td>${item.quantity}</td>
<td style="width: 60px;">
<button type="button" class="btn btn-block btn-sm btn-outline-primary"
onClick="cartLS.quantity(${item.id},1)">+</button>
</td>
<td style="width: 60px;">
<button type="button" class="btn btn-block btn-sm btn-outline-primary"
onClick="cartLS.quantity(${item.id},-1)">-</button>
</td>
<td class="text-right">$${item.price}</td>
<td class="text-right"><Button class="btn btn-primary" onClick="cartLS.remove(${item.id})">Delete</Button></td>
</tr>`).join("")
$total.innerHTML = "$" + cartLS.total()
}
renderCart(cartLS.list())4. Rerender the shopping cart when the product list has changed.
cartLS.onChange(renderCart)
5. Add items to the shopping cart.
cartLS.add({
id: 1,
name: 'CSS',
price: 100
})
cartLS.add({
id: 2,
name: 'Script',
price: 200
})
cartLS.add({
id: 3,
name: 'CSSSCRIPT',
price: 300
})6. List all items in the shopping cart.
cartLS.list();
7. Check if an item is in the shopping cart.
cartLS.exists(id);
8. Remove an item from the shopping cart.
cartLS.remove(id);
9. Update an item in the shopping cart.
cartLS.update(id, property, value);
10. Increase/decrease an product’s quantity.
cartLS.quantity(id, diff);
11. Get the information of an item.
cartLS.get(id);
12. Get the total price.
cartLS.total([reducer]);
13. Destroy the shopping cart instance.
cartLS.destroy();
Changelog:
v1.1.5 (04/26/2020)
- Rebuild








Hello Peter,
I was trying to reach you but in the github you did not provide any contact information.
I am trying to use your Cart script to integrate into my website, but some questions arises, do you have any communication channel or direct email ?
thanks
Salih Akca