JavaScript Shopping Cart Tutorial for Beginners
Key Takeaways
This video tutorial demonstrates how to create a shopping cart using JavaScript, covering topics such as DOM manipulation, event listeners, and cart management. It provides a step-by-step guide on how to build a functional shopping cart, including adding and removing items, updating quantities, and calculating totals.
Full Transcript
hello everybody welcome to my video on how to code a shopping cart using only vanilla JavaScript on the right here we have the final project of what we're going to code in this video we have these items that we have a button to add them to our cart and down here we have our cart so if we click Add to Cart it'll add an item to our cart and update the total price increasing this quantity will also increase the price decrease and it will decrease the price and removing it will allow us to remove the item from the card we try to add a item to the cart multiple times it'll tell us that we've already added this item to our cart so we can't do it again and then if we click purchase down here they'll tell us thank you for the purchase and then remove all the items from our cart simulating a purchase so if you guys are just joining in on this video all of the code for creating the styles for this page as well as the HTML can be found in videos linked in the description or in the info cards in the corner so let's get started with actually coding of what we have here by opening up our store dot HTML page over here with live server to see what we have started to get working with so over here you see we have the shopping cart items as well as we have some items just templated endure a shock for now but none of these buttons actually do anything and change in these quantities doesn't update our total down here so we need to get started coding this with JavaScript in order to do this we need to create a new file in our project and we'll just call it store J S which stands for a JavaScript file so the dot J extension tells us that this is going to be a file with JavaScript in it then in order to include that file inside of our store dot HTML we need to go into our head and include a script tag here and give it a source attribute and this source attribute works exactly the same as href attribute for path or URL we add to it so we just say the path to are stored on a J's file here and then we end this tag and we do need an ending tag in our script tag unlike the link tag which is self closing and that's because you can actually put JavaScript inside of the script tags but it's always suggested to use a JavaScript file as opposed to JavaScript inside of a script tag similar to using a style element as opposed to an external CSS stylesheet so now if we save that our Styles from our JavaScript from our store dodgiest is now being loaded into our page but it's actually do anything because there's files empty in order to see these changes we can use console.log which will write anything that we put inside of here into the console of our web browser so if we just put here save that and then over on our browser if we right click and click on inspect we can now view the console so here you see if we wrote here to the console which means that we are actually running all the JavaScript inside of our store dodgiest we can change this to here to save it and now you see here to is output it to the console now before we get started I do want to make a note that in are stored out HTML we're loading our script tag inside of the head of our HTML and this means that our script tag will load before all of the content inside of our body in general things inside of the head will load in the background while the body of your page is being loaded but script tags are different in that while a script tag is being loaded nothing else on the page can continue loading in order to get around this and make our script tag load in the background we need to add the async attribute here which tells our browser in order to download this storage AS page in the background and continue downloading the actual body of our HTML page at the same time now let's jump into our storage AS page and start coding up the actual interactivity for our website so inside of here the very first thing that we're going to want to do is make these remove buttons here actually remove our item from our cart so the first thing we need to do is we need to select these remove buttons and then add an event to them to say when this is clicked do something so instead of our straw dot HTML if we scroll down to the section for our cart right here you see that we have this button danger class applied to all of our buttons so we want to select all of the buttons in our document that have this button danger class in order to do that we're going to use the document object which is an object that JavaScript gives to your page that essentially says this document object is everything inside of your HTML it has a bunch of methods on it for querying the different objects on your page as well as adding new objects to your page so we use this document object going to call the method on it which will allow us to query elements based on classes so we're gonna say give elements by a class name and all we do inside of here is we pass the class name we want to query for so in our case this is button danger and this method right here is going to return all of the different elements on our page that have the class but danger we're just going to save that to a variable and we'll say that these are the remove cart item buttons so now this variable remove cart item buttons stores all the different buttons with this exact class on it in order to see that we can log this variable right here to the console and if you say that we see that we now have inside of this array two different buttons and if I hover over them you see that they get highlighted inside of the actual browser you see the top one is highlighted and the bottom one is highlighted here which is perfect that's exactly what we want so now what we need to do is we need to add the exact event listeners to these in order to do something when we click on them to do this we need to loop through these different objects so we're going to use a for loop we'll save for variable I equals 0 so starting at 0 while I is going to be less than the length of the number of buttons we have so while I is less than the length the buttons we have and then we'll add 1 to I every single time instead of our loop so essentially all this code is saying is loop through all of the different buttons inside of our cart we'll create a variable here that will be the actual button so which call button will set it equal to whichever element in the loop that we are in because I will constantly be having one added to it each time we go through this array so we're going to select the il iment of this array set it to this button element here so now we can use button and since this button corresponds to one of our remove buttons over on the right here all we have to do is say button dot add event listener and this is how we add a listener to tell us when we click on a button do something so in our case we're going to listen for the click event and when the click event happens we want to run some code so we'll create a function for them and for now we're just gonna log to the console and we'll just say clicked and if we save that there we go click now when we click on a button you'll see that in the console it logs that we clicked and every time we click on it it'll block that and it would for both lower buttons so that's perfect that's exactly what we want now all we need to do is make it so this function will actually remove the cart item from our cart in order to do that we need to take our function here and this event listener always returns an event object inside of the function that it calls and this event object has a property on it called target so we can say event dot target and this target is essentially whatever button we clicked on so we'll just use our variable here and we'll say button clicked it's going to equal that so the button that we click is this event target and what we want to do is we want to get the cart row that buttons inside so if we go to our store here we have our button object here the parent of it is this object and then the parent of that object is the entire row which is what we want to remove from our cart so I'm deciding here we're gonna use button clicked and we want to get the parent element which is going to be this div right here that cart quantitative and then we want to get the parent of that in order to get the entire cart row so we send out parent element again and this is going to be the cart Road that we want to completely remove so we'll just use the remove function there we go and if we save that now when we click on this remove button it'll completely remove that item from the cart and there you go you see it's completely remove that item from the cart if we click this one it'll do the same thing but you'll notice our total here is not actually being updated so we need to write some code in order to update the total of our cart every time we remove an item from it in order to update the total of our cart let's create a brand new function down here we're just going to call it update cart total there we go and we can just call this function inside of our event listener for our button so we can say update cart total and now this will run all the code inside of this function when it's called so what we want to do in this update cart total function is we want to go through every single row in our cart we want to find the price and we want to multiply that by the quantity and then add that together for every single one of our rows and display it down here and our total so the first thing that we want to do is we want to get all of our cart rows and if we look over in our store dot HTML you'll see that all of our cart rows are inside of this cart items and they all have this cart row class so what we can do here is we can say we want to get our cart item container and this will be equal to the document dot get element by classman like I said and we want to get the elements that have the class name of cart item cart items sorry because that right here is what wraps all the rows inside of our cart but we only want to get the very first one of this cart items because this get elements by class name returns an array of elements and we only want one so we're just going to select the very first element inside of that array as our cart item container and then inside of that cart item container we wanted to use this same method of getting the elements by clasping and we want to get all the different cart row elements so elements that have the class cart row that are inside of this cart item container using this get elements by class main method on an actual object will only get the elements inside of that object that have this different class so then we can just set that to a variable we'll just say that this is our cart rows and now all we need to do is loop over all these different cart rows very similarly to how we looped over all the buttons up here so I'll just copy this code paste it down here and change this to be cart rows since we want to loop over our cart rows and then we'll just say create another variable here that'll be our cart row and we'll set that equal to whichever item we are inside of this array so whichever row that we're currently inside of this array is what this Cartwright 'm will be and then all we need to do is get the price and the quantity for the row of this cart so if we go back to our start at HTML you can see that our cart price is inside of this object with the class of cart price so what we're going to do is we're going to create another variable we'll call this one the price element and we'll set that equal to the cart row and we're going to get element by class name again and we want to use cart price here in order to get that element that contains the cart price and we just want the very first one again just like we used with the cart items and now we need to do the very next thing with the quantity and the quantity in here is this input element with the class of cart quantity input so we're going to do the very same thing to get a quantity element we're going to get it from the cart row where the element has the class name of cart quantity input and again we only want the very first one so we'll just use that and now we have our price element and our quantity element and if we log these out to the console so we have a price element and a quantity element if we save that and now when we remove an element it'll tell us oh here's our span for our price right here and here's the input and if we hover over them you'll see that is returned all of the different priced elements and quantity elements inside of the row which is exactly what we want so now all we need to do is get the actual information from these elements because currently we have the element and not the information inside of it so we want to do is we want to get the price from the price element so we'll say price and we're going to set that equal to the price element and what we're going to do is get the inner text from that element the inner text we'll just get whatever text is inside of that element so we can do here as will do another log to see what this is actually returning and when we click this remove button you'll see that it's returning this 999 which is the text inside of this price column which is exactly what we want but you'll notice this 999 has a dollar sign in the beginning and we want this to be a number without the dollar sign so what we need to do is we need to just do a replace on this we want to replace all the dollar signs inside of this string and we were on place them with absolutely nothing so those will just completely remove the dollar sign from our string and then since we want this to be a number and not a string we need to use the parse float method which will turn any string into a float which is essentially a number with decimal points after it there we go and now please save that and do this remove again you'll see we now have 999 as a number without the dollar sign which is exactly what we need in order to do math on this number the last step is to get the quantity from our quantity element so we're going to say quantity equals the quantity element and we want to get the value of the quantity element since this is an input element right here you need to get the value property of it and not the in there text because inputs do not have any text inside them they have a value so we want to get the value here which is going to correspond with this quantity number and now we can just say price times quantity and we can blog that so now if we click remove here you see we get 1998 which is this price times this quantity and that's perfect now the very last thing we have to do is set this value to whatever we get for the price and quantity and since this is inside of a loop we need to total all of these together so before our loop let's create a variable we'll call it total and we're going to set this to zero to start with and then we want to add so total is going to equal total plus the price times the quantity and it'll do that every time it goes to the loop it'll add the previous total to the price times quantity of that row to give us the new total and then after our loop at the very end here we want to actually get the element with the card total price so if we go over to our store here you'll see that we have this cart total price class which is where this price comes from so we'll just do document dot get elements by class name give it that class our total price again we only want the very first one and then we want to do is we want to set the inner text of this element so we do inner text and we're going to set it equal to the total and now if we save that and we click remove you see that our total is updated to the actual quantity times price of everything inside of here but you'll notice there's no dollar sign so what we can do in here as we can use the dollar sign and then combine that with our total and now if we save that and remove you'll see that now our total updates and is displayed correctly with a dollar sign in front of it now before we go further with actually creating the rest of our buttons I do want to make note of one thing that is particular with JavaScript that we need to make sure of before we actually start trying to access the different elements on our page we need to make sure that our page is done loading if you remember when we added this script tag we added this async method here which tells it that it'll load in the background while the body of our element is loading but if the body of our page loads after the JavaScript loads our JavaScript will run here but there's no body for it to run off of which means it won't be able to find any of these different elements since they haven't been generated yet so in order to check to see if the page is done loading we need to go to the very top of our javascript file here and we need to add an if statement to check to see if the document and we're going to check the ready state to see if it is still loading so if the document is still loading which is what this if statement is same what we want to do is we want to add an event listener to our document very similarly to how we add in an event listener to our button and we want to listen for the event Dom content loaded and you have to make sure that you have the capitalization correct for all of these different letters in order for this to work and this event will fire as soon as the page is done loading so inside of here we just want to run a function and we'll just call that function ready and then if our page is already loaded so if the page is loading it'll run the code in here but if it's not loading so if it's already done loading we just want to run that ready function no matter what and then we can create that function will call it ready here and inside of this function will do all the code for hooking up our buttons right here and that way our code for hooking up the buttons will automatically work even if the page isn't already loaded because it'll just wait for this event of the Dom content loaded before it actually calls the ready function so now we know everything inside of here the page is already loaded when the code gets to this point another thing we can do is we can clean up our code a little bit by creating a function and we'll just call this function here we'll call it remove cart item and this function will take all the code that is inside of our event listener here for removing a cart button we'll add the event object in here and inside of our click right here we'll just put remove cart item so now instead of having all the code for our function inside of the event listener here we're able to move it out here so it's easier to tell what's going on in our code and easier to read and if we reload the page you'll see that everything still works as before the next thing that we can work on is making it so that when we changed the value inside of the quantity here that it will actually update our total because as you see if I increase this number our total stays the same and we can also input numbers below below zero which we do not want to be able to do because we don't want someone to order negative 14 t-shirts so what we're going to do is we're going to do something very similar to what we did with our card buttons here but we're going to do it for our quantity input so let's go back to our store dot HTML page scroll down to our cart you'll see we have this card quantity input class on our input which we can use to select those elements so we'll create another variable we'll call it our quantity inputs and we'll set it equal to the document dot get elements by class name for that classman and then we'll just loop over them again just like we did with the remove Cart button so I'll copy that and use quantity inputs instead of our removal buttons and then in here we'll set a variable input equal to whichever iteration of the loop that we are on will get that element from the array so now this is going to be each one of our inputs that we are going to have for our quantity inputs right here and now all we need to do just take that input we need to add an event listener and inside of here we want to add the event listener change in order to listen to any time the input changes its value and then we're going to call a function and we'll just call it quantity changed there you go and now let's create that function down here so we have a function quantity changed and it'll take that event variable that we talked about earlier and there we go now we can actually code up what we want to do when our quantity has changed so the first thing we need to do is get that quantity element so we're just going to get that input here and we're going to set it to event dot target since we know that the target of our event is going to be the actual input element that we need and then we want to check to see if the value inside of this input is a valid value so the first thing we want to check for is we want to check for if it's actually a number because if the person deletes it and clicks off this is no longer number so we can use the function is n a n which stands for is not a number and we can pass in our input dot value in here and this will check to see if our input is a number or if it's not a number and we also want to make sure that our number is not a negative number we want to make sure that it is 1 or higher because we always want people to order at least one of something you can't order zero or negative one of anything so we can check to see if it's not a number or if the input value is less than or equal to zero which means that they either put zero negative one negative two anything less than 1 inside of here what we want to do is we want to set our quantity or our input value we want to set it to 1 since 1 is the lowest possible number we want somebody to be able to purchase an item of and then all we need to do after that is update the total inside of our car since we already created this function we don't actually need to do anything other than call it and now when we save that if we increment this value to two for example you'll see that our total increases if we increment it to three you'll notice our total increases again for five and so on but you'll also notice that our price here gets a little bit messed up it has a ton of nines at the end here and we don't actually want that this is because in computers they can't do division or multiplication or addition with floating-point numbers so pawn numbers with decimal points 100% accurately so sometimes they get rounding errors where you'll get a bunch of nines or a bunch of zeros and a one saying that it didn't quite round out exactly right so what we want to do instead of our update card total function is we always want to round to two decimal places so in order to do this we're going to take our total variable here and we're going to set it equal to our total variable again but we want to round it this will use the map that round function which will round to the nearest whole number but since we want to round to two decimal places well first multiply our total by 100 which will move our two numbers after our decimal place in front of the decimal place we'll around it and then we will divide by 100 and this will essentially round our total to the nearest two decimal places and if we save that now when we increment this total our quantity you'll notice our total never actually goes beyond two decimal places even if there's a little bit of a rounding error you'll also notice that if I try to lower this number below one and click off it'll always change back to one for example if I do negative one here it'll be back to one if I put in zero back to one and even if I completely delete it and click off it'll change back to one this is exactly what we want this means that our users will never be able to order less than one of an item that's in the cart and if they want to remove it from the cart all they have to do is click the remove button and would be removed for them now the next button that we have to hook up is just Add to Cart button that all of our different cart items have the first thing we need to do in order to accomplish this is the very same thing that we needed to do for our quantity inputs and a remove cart item button we need to go up we need to find where this button is so right here we have shop item button is a class we apply it to all of our different Add to Cart buttons so down here we're just going to create a variable which is our Add to Cart buttons we're going to set that variable equal to the document get elements for the class name of the shop item button and then we're going to do another loop over these objects so we'll just copy this loop from up here we're going to replace quantity inputs with the Add to Cart buttons since we want to loop over these buttons for adding to cart we're going to get the actual button so we'll say the button is equal to Add to Cart buttons the ID element since that'll be whichever element of the for loop that we are on and then the last thing we need to do is we need to add the actual event to the button so let's say a button that add event listener we want to do click again since we want to do something when we click on the button and then we need to give it a function name and we're just going to create a function called add to cart clicked and there we go now let's create that function down here say function add to cart clicked it'll take that event parameter and then we can do again create the sexual button so we'll say the button here is going to be equal to even top target and this is our Add to Cart button now so now if we scroll down to a cart we can see that there is a few elements we need to add to our cart we need to add an image we need at a name of the item the price of the item and then the quantity and foot as well as the removal button this quantity input is always going to be 1 and this remove button is always going to be just to remove button so really all we need to do is get the price name an image from our actual item so if we go back to our HTML here and we find a shop item we can see that our Add to Cart button is inside this details div and then our actual shop item is the div right above it so what we need to do in order to get our sharp item as we say shop item we're going to set that to our button and we're going to get the parent of the button and the parent of the buttons parent and that will be this shop item div right here and from here we can query the item inside the shop item did to get this shop item title for example so if we go back here we can say that the title is going to equal to this shop item we're going to get two elements by class then with the class name of shop item title and again we just want the very first one and we want the text inside that so we use inner text and if we do a console dot log here of the title save that and we click Add to Cart you'll see we get coffee cup for the coffee cup get t-shirt when click the t-shirt button and so on for all of our different buttons so now what we want to do is we want to get the price next if we look here we have the shop item price class which we can query on so we can say that the price is going to be equal to shop item get elements by a class for the shop item price class again get the first element and get the text inside of it and now if we log the price and the title to see there the coffee cup 699 this t-shirt $19.99 and so on now the very last thing we need to do is we need to get our image element and all we want to do is get the source of our image so one side of our store here we see that our image has the class shop item image so if we do the very same thing again we can say that the image source is going to be equal to shop item get the elements with the class name shop item image get the very first one and instead of the text inside of this image since images don't have text we want to get the source attribute and this attribute is going to be the source that we applied to our different image so now if we print this out here we say image source click the Add to Cart button you'll see that we get the URL that goes towards the source of our image which is exactly what we want and it's going to be different for all of our different images as you can see so now what we need to do is we need to actually add a row to our cart down here and this is going to be the most complex part of what we're going to do so I'm going to create a separate method to do this and we'll call this the add item to cart method and we're going to pass in the title the price and the image source into this function I'll just create this function down here add item to cart and it's going to take the parameters title price and image source just like that and now we need to do is we need to create a row for our cart item in order to create this cart row we'll just create a variable called cart row and we need to set it to a new elements we're going to use document dot create element which allows us to create an element of any type that we want so for example we just want to create a div so if we run this document create element it's going to create a brand new div it's not going to add it to our HTML yet but we have a div that we can now later add to our HTML and we want to add it to our cart items as you can see here we scroll down we have a cart items which is where all of our cart rows are going to be so we want to add that to our cart items so we're gonna find the cart items which is going to be equal to the document we're going to get elements by class name for cart items and we're just going to get the very first one and then we're just going to use the append method for this cart items so we say pend which is going to add this cart row to the very end of our cart items so we can just say cart row here and now this append method will append our cart row to the end of our cart items which is exactly what we want it's just going to add an empty div though for now so if we click this Add to Cart button we're adding emptied is which have nothing in them but if we wanted to add something into these divs just to see what it looks like we can say cart row inner text equals title and now when we click this add to cart button you'll see we add a coffee cup here if we click the t-shirt one we added a row a t-shirt and so on and now all we need to do is do the actual styling add the image and add the price etc so we get our cart row looking exactly like our other cart rows and the easiest way for us to do that is to just take the HTML directly from our store page here so we'll just copy everything that's inside of our cart row and we're going to actually use that HTML generate a cart run so we'll just say that our cart row contents variable we're going to set it equal to a string but we're going to use back ticks around the string instead of quotation marks so we can use our string on multiple different lines so now if we paste this in here fix our space in real quick there you go you'll see that we have all of the different HTML that we need to create our cart contents so now instead of setting the title here what we want to do is we want to set the cart row inner HTML we're going to set it to our cart row contents and the reason we use inner HTML is because we're actually using HTML tags inside of this instead of just text and now we save this click Add to Cart you see that we added a new item to our cart which is perfect but you'll notice that it's actually not styled just like this and that's because we need to add the class of cart row to our cart row here so we can just say cart row dot class list dot add and we'll just add the class of cart Road save that and now when we click Add to Cart you'll notice that add something to the cart but you'll notice it always adds the t-shirt item and that's because we're not using the variables we pass into this function since we used back ticks here we can actually just put variables directly into our code so for example our image URL if we put a dollar sign and then a curly bracket anything inside of that is going to be a variable that will evaluate so we'll say the image source so now it'll take our image source variable and put it right here inside of this HTML we can do the same thing for the title down here so we'll save title and then lastly we can do the same thing for our price right here and now if we save them we click Add to Cart you'll see that it now adds all these elements correctly to the cart like we want to let me click Add to Cart again you'll notice that actually add two coffee cups to our cart which we don't want to do so what we want to do is we want to make a check to check to see if we already have the coffee cup inside of our cart before adding it to our car in order to do that we're going to get all the names of our card items from our part so we'll just say cart item names we're gonna set that equal to carte items dot get element by class man and if we check to see what our class name is in here we'll notice that it is cart item title right here will be the name of our cart item so we can just get by a car item title and then we can loop through all these different card items so let's say while I starts at 0 I is less than carte items length and then we add one to I every time we go through the loop and then we can just say that our cart item names so we check if cart item names we want to get the ith element or whatever iteration wrong we want to check the inner text because the inner text will either be t-shirt in this example album three depends on whatever rover on and we want to check is the text inside of that cart row equal to the title that we passed in right here and if it's equal to the title that means that we've already added that item to our cart so we want to just alert the user with the alert function and the alert function will pop up a pop-up for the user telling them that something has happened and they can click OK to dismiss the pop-up so we'll just say that this item is already added to the cart there we go and then we also want to return from our function since we no longer want to execute the code below this for loop and calling return will immediately exit you out of the function and stop executing anything below it so call and return here will bring us back to where we called that ID item to cart function so now if we save that we add a coffee cup you'll see it adds it perfectly down here and if we try to add another coffee cup we're going to get a message thing that the item has already been added to the cart and you'll notice it does not add another one to the cart which is perfect you will notice however that our total down here is not being updated so well in our Add to Cart clicked button event right here we'll just put our update cart total function right there and now if when we add a coffee cup you notice that our total updates correspondingly with our coffee cup items one thing that you will realize though is if we go to use the remove button on our newly added item you'll notice our remove button does not work and you'll think why does that not work we added all of our event listener up here when our document loaded but we only added these event listeners as soon as our document loaded and this remove button was not here when the document loaded this was added after we loaded the document so we need to add an event listener to this remove button so inside of our function here after we add our contents to the document we're going to select them will say cart row we're going to get the elements by clasping and we're going to do it for the button danger which is a remove button we want to get the very first one and we'll add an event listener here for click just like we did above when the document was loaded and we'll use our function for removing a cart item now if you save that if we add this coffee cup and then we click the remove button you'll not notice that remove button works we now need to do the same thing for our quantity since as you can see our quantity input does not work it does not update the total so we'll just do the exact same thing with the cart row we'll get elements by classmen and in this case it's the cart quantity input get the very first one here add the event listener and this time the event listener is a change event listener instead of the click now we'll just use our quantity changed function and now when we added something to the cart these two lines will be run which add our event listeners to our new quantity input and our new remove input so now when we update our quantity input our total will update and our remove button will now remove the item from our cart this is exactly what we need but what we should do is remove these elements from our HTML since we don't want our cart to already have items in it as soon as the page loads so we'll go into our store here and remove all of our cart rows inside of our cart items now if we save that you see that our cart is completely empty oh we should update our price here as well to start at $0 and now you'll see that our cart is completely empty when I page loads and we can add items to our cart increase the quantity of those items maybe add a different item to the cart and you'll see that this adds up perfectly total right here is perfect you can remove things as we need to remove it back to zero whatever we need now the very last thing we have to do is to make the purchase button actually remove all the items from our cart so let's start to do that now inside of our ready function here we're going to do the exact same thing we've done for all of our other buttons and we're going to add an event listener so let's check what class we need to query on we want to look for this button purchase class and that is the class that we applied to our button so in here we're going to do document dot get elements by class name we're going to use that class name of button purchase there's only one button for purchasing on our entire page so we just want to get the first one and we're gonna add the event listener to this it's going to be a click event listener and we're going to make a function and we'll just call it purchase clicked just like that and down here you can add that function purchase clicked there we go and all we want to do inside of this function is alert the user that they have purchased these items so I'll create an alert and inside of this alert will just say thank you for your purchase this will just notify them that they have purchased these items and then we will go down here and we will delete all the items inside of our cart so in order to do this what we want to do is we want to select the container our cart items are in which is this cart items class right here we know that all of our cart rows are going to be added to this so we will say cart items as a variable it's going to be equal to the document we're going to get all the elements by class then of cart items we know there's only one so we're just going to get the first one and then we're gonna want to loop over all the children inside of the cart so if we add a bunch of things in the cart you see that we're gonna have multiple cart rows in here so we want to check for all the children inside this cart items so we'll say while which is similar to a for-loop but it will continue to execute as long as whatever is inside the parenthesis here is true so we'll say while our cart items has children so has child note which essentially means is there any children inside of this cart Adam if that is true we're going to take the cart item we're going to remove the child and we're just going to remove whatever the very first child inside of cart items is and we can use the first child property to get that so this while loop will continually loop through all of the I rows in our cart items and remove them from our cart items until our cart items is completely empty so let's test this out let's add some things to our cart here we'll increase the quantity here so we have 67 dollars worth of purchases to make if we click purchase it'll say thank you for your purchase and we would click OK you'll see everything our cart is removed but our total still hasn't been updated so again we're just going to call our update cart total function at the end of here and now we add some things to our cart look at our total 2698 purchase after we click OK our total goes back to zero and that's all there is to creating the JavaScript for this page it may seem like a lot of code we have a lot of lines in here but a lot of this is just doing the same thing over and over again as you can see we have get elements by class name being called all the time to get the elements that we want to apply our events to as well as to get the elements that we want to get the text from in order to create our rows or remove our rows really the main takeaways from here is up here we have the code that is going to check to make sure that our document is loaded before we try to access the different parts of it this is incredibly important to have in every single bit of JavaScript that you work on then next we set up all of our event listeners for all of the items that are already loaded into our document at the very beginning of our document load then we have our different events that are going to do different things such as add elements to the cart remove elements from the cart update the quantity and so on and then lastly when we add new elements to our document we need make sure to hook up all of our event listeners to those documents elements because they weren't around when we set up our initial events up here in our ready function because they were added after this ready function was called this is a very important step to add these event listeners that has commonly forgotten when creating new elements in JavaScript other than that though there really isn't much complicated code in this project and really not much JavaScript specific code all we're really doing is getting the different elements and then pasting those elements inside of our cart and then removing them with this purchase button or the remove button so now if I make this a little bit larger here remove this console down here you can see we can add our different items to our cart change our quantity as high as we want we try to make it a negative number it'll change it back to one maybe we don't want a coffee cup remove it and then we're done purchase our items and there we go this is everything that we need in order to create the fully functioning cart on our band website so thank you guys very much for watching this video I hope you guys learned something about the JavaScript that you need to use in order to create this cart from just plain vanilla JavaScript if you guys want to see the code that I have for either the actual band web pages or the cart itself go over to my github which is linked in the description below for all of the code that we worked on in this lesson thank you guys very much for sitting through this extremely long video on JavaScript if you guys enjoyed it please don't forget to leave me a like and subscribe if you want to see similar content and let me know down in the comments below what you want me to cover more in depth related to JavaScript in the future thank you guys very much have a good day
Original Description
*Master DOM manipulation* with my *FREE DOM Manipulation Cheat Sheet* - _20+ methods_ 👉https://webdevsimplified.com/js-dom-manipulation-cheat-sheet.html
*Become a web developer* with my *FREE Web Development Roadmap* - _260+ videos, 120+ projects, 60+ articles_ 👉 https://webdevsimplified.com/web-dev-roadmap.html
In this video we will learn how to utilize JavaScript to add functionality to a shopping cart. We will cover how to check if the document is loaded, and how to query the document for elements by class, how to add events to elements. We will then combine all of these techniques to make the shopping cart in our web page work in an intuitive way.
Also, let me know if there are any other JavaScript topics you want me to cover in further depth.
Starting Code:
https://github.com/WebDevSimplified/Introduction-to-Web-Development/tree/master/Introduction%20to%20CSS/Lesson%203
Finished Code For:
https://github.com/WebDevSimplified/Introduction-to-Web-Development/tree/master/Introduction%20to%20JavaScript/Lesson%201
Make The Shopping Cart Accept Payments:
https://youtu.be/mI_-1tbIXQI
Band Website HTML Series:
https://www.youtube.com/watch?v=BvJYXl2ywUE&list=PLZlA0Gpn_vH8BoXcpCUvdmdPZFuR5y2lV&index=1
Band Website CSS Series:
https://www.youtube.com/watch?v=Sv_NAxi_jNs&index=2&list=PLZlA0Gpn_vH9D0J0Mtp6lIiD_8046k3si
Twitter:
https://twitter.com/DevSimplified
GitHub:
https://github.com/WebDevSimplified
CodePen:
https://codepen.io/WebDevSimplified
#Javascript #WebDevelopment #ShoppingCart
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Web Dev Simplified · Web Dev Simplified · 21 of 60
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
▶
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
Introduction to Web Development || Setup || Part 1
Web Dev Simplified
Introduction to Web Development || Understanding the Web || Part 2
Web Dev Simplified
Introduction to HTML || Your First Web Page || Part 1
Web Dev Simplified
Introduction to HTML || Basic HTML Elements || Part 2
Web Dev Simplified
Introduction to HTML || Advanced HTML Elements || Part 3
Web Dev Simplified
Introduction to HTML || Links and Inputs || Part 4
Web Dev Simplified
Learn Git in 20 Minutes
Web Dev Simplified
5 Must Know Sites For Web Developers
Web Dev Simplified
10 Best Visual Studio Code Extensions
Web Dev Simplified
Learn CSS in 20 Minutes
Web Dev Simplified
How to Style a Modern Website (Part One)
Web Dev Simplified
How to Style a Modern Website (Part Two)
Web Dev Simplified
3D Flip Button Tutorial
Web Dev Simplified
How to Style a Modern Website (Part Three)
Web Dev Simplified
Animated Loading Spinner Tutorial
Web Dev Simplified
How to Write the Perfect Developer Resume
Web Dev Simplified
Animated Text Reveal Tutorial
Web Dev Simplified
Learn Flexbox in 15 Minutes
Web Dev Simplified
Custom Checkbox Tutorial
Web Dev Simplified
Start Contributing to Open Source (Hacktoberfest)
Web Dev Simplified
JavaScript Shopping Cart Tutorial for Beginners
Web Dev Simplified
Responsive Video Background Tutorial
Web Dev Simplified
1,000 Subscriber Giveaway
Web Dev Simplified
How To Prevent The Most Common Cross Site Scripting Attack
Web Dev Simplified
Transparent Login Form Tutorial
Web Dev Simplified
The Forgotten CSS Position
Web Dev Simplified
How to Code a Card Matching Game
Web Dev Simplified
10 Must Install Visual Studio Code Extensions
Web Dev Simplified
Learn CSS Grid in 20 Minutes
Web Dev Simplified
Learn JSON in 10 Minutes
Web Dev Simplified
10 Essential Keyboard Shortcuts For Programmers
Web Dev Simplified
What Is The Fastest Way To Load JavaScript
Web Dev Simplified
Differences Between Var, Let, and Const
Web Dev Simplified
How To Install MySQL (Server and Workbench)
Web Dev Simplified
Learn SQL In 60 Minutes
Web Dev Simplified
How To Solve SQL Problems
Web Dev Simplified
What Are Design Patterns?
Web Dev Simplified
Null Object Pattern - Design Patterns
Web Dev Simplified
Your First Node.js Web Server
Web Dev Simplified
How To Setup Payments With Node.js And Stripe
Web Dev Simplified
How To Learn Any New Programming Skill Fast
Web Dev Simplified
Asynchronous Vs Synchronous Programming
Web Dev Simplified
JavaScript ES6 Arrow Functions Tutorial
Web Dev Simplified
Are You Too Old To Learn Programming?
Web Dev Simplified
JavaScript Cookies vs Local Storage vs Session Storage
Web Dev Simplified
JavaScript Promises In 10 Minutes
Web Dev Simplified
Builder Pattern - Design Patterns
Web Dev Simplified
JavaScript == VS ===
Web Dev Simplified
JavaScript ES6 Modules
Web Dev Simplified
8 Must Know JavaScript Array Methods
Web Dev Simplified
CSS Variables Tutorial
Web Dev Simplified
JavaScript Async Await
Web Dev Simplified
How To Choose Your First Programming Language
Web Dev Simplified
Easiest Way To Work With Web Fonts
Web Dev Simplified
Singleton Pattern - Design Patterns
Web Dev Simplified
Responsive Navbar Tutorial
Web Dev Simplified
CSS Progress Bar Tutorial
Web Dev Simplified
Learn GraphQL In 40 Minutes
Web Dev Simplified
What is an API?
Web Dev Simplified
Learn How To Build A Website In 1 Hour!
Web Dev Simplified
More on: Prompt Craft
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
Had my Frontend Developer interview with Capgemini (Application Developer) today, and I wanted to…
Medium · JavaScript
10 Frontend Developer Tools to Boost Productivity in 2026
Medium · Programming
10 Frontend Developer Tools to Boost Productivity in 2026
Medium · JavaScript
The US Frontend Engineer Market in 2026: A Data-Driven Reality Check (and the Bias That Stops Us Seeing It)
Dev.to AI
🎓
Tutor Explanation
DeepCamp AI