In the previous article, we talked about the importance of showing the number of items in a cart when it comes to conversions. Dynamically updating the number of items and their prices in a shopping cart allows the users to see the final price and correct the number of items they want without having to load another page. One of the biggest reasons for the shopping cart abandonment is the delay in loading a page, even if it is only 2-3 seconds. Refreshing the page every time a shopping cart updates will make people impatient and more likely to cancel their order. Updating the cart dynamically and showing users all the details such as the subtotal, tax, shipping rates and the total amount of the order however will make it much easier for them to see every cost detail of their transaction and just hit the final Order button. In this tutorial, we'll show you how to build a dynamic shopping cart using Bootstrap and JQuery.
The external CDN links below are for Bootstrap CSS, Bootstrap JS files and JQuery as well as FontAwesome. Copy and paste them and put them in the head section of your project's file:
cart-total: The total amount after everything is added such as the subtotal and taxes.
- pass-quantity: the number of items specified in the dropdown
- product-line-price: The subtotal of each specific item. For example, if the item is initially $50, it will display as 50 and if the number of items is increased to two, it will display 100.
- #cart-subtotal: The subtotal amount
- #cart-tax: The tax rate
Each item is inside a div container with a classname of
The CSS for this cart is pretty minimal as the bulk of the styling is done via built-in Bootstrap classes.
Now that we built the structure of the shopping cart and added some styling, it is time to make it dynamic. You can put the code below inside your HTML file between script tags or create a separate file and link it from the HTML file. We start by giving a value to the tax rate. Next, we have two functions, one that selects each input, gets the value inside that input and updates the numbers based on change and the other one that removes the item by clicking a button. After we do all the calculations to display the price, we use the
fadeIn() JQuery method changes the opacity of the selected elements so when the changes are applied to prices, they will all have a fading effect to give the feedback that they were changed. You can change the fading speed by changing the
fadeTime variable to a different number.
And there it is. Check out the JSFiddle below and use the dropdowns to see how the cart gets updated: