It's time to face Javascript down and say "I'm not afraid of you anymore!"
I'll be using Javascript to add functionality to my shop page (which I finished styling in CSS yesterday).
I created my store.js file and added it with <script> tags to the <head> of my store page.
In my Javascript file, I typed console.log("here") and opened the console on my browser. That way I can see what processes are occurring on the page.
I added the link to my .js file in my head which means it'll download before the body of my page downloads. In order to set my page to download content first and then Javascript, I added the async property. This means the page will load faster.
The first thing I'm going to work on is funcitonality of the remove buttons from the cart. I need to select the remove buttons and add an event to say "when this is clicked, remove the item".
I used the document object to "find" the btn-danger class from the remove button, since we want to select all of the red buttons on the page. I added the method getElementByClassName to the object.
I then set these buttons as a variable in Javascript.
var removeCartItemButtons = document.getElementsByClassName("btn-danger")
I also added a console command so that I can see what elements are being selected in my browser console window.
console.log(removeCartItemButtons)
I've dabbled with Javascript before. I feel that I get the basics, but don't really understand how lines of code are built up to create a functioning webpage.
The console - something I am just learning about - will be incredibly useful as I build sites. It will allow me to 'look behind the curtain' to try to figure out what is going on.
I need to add "event listeners" - which I assume are what they sound like, bits of code which listen out for an event and do something when the event happens.
To do this, I'm using a for loop which will cycle through all the buttons, checking if the event has happened yet (eg the button is clicked), and if it has, doing something (eg removing the item(s) from the cart.
for (var i = 0; i < removeCartItemButtons.length; i++) {
var button = removeCartItemButtons[i]
button.addEventListener("click", function() {
console.log("clicked")
})
}
The above is saying "For a variable i, start at zero. When i is less than the total of removeCartItemButtons, add one to i (move to the next i). When on a value of i (ie one of the buttons), add an event listener object called "click" which does a function." At the moment, the function is a console read out, but it will be changed later.
Functions consist of events and targets. (I don't really know what this means). I feel that Javascript has a lot to do with giving more complicated code a name so that you can reference it later. So I've created a new variable called "buttonClicked" which is equal to the event.target.
I then need to find the target of this event (which will be the entire row of the cart, since I want to remove the whole row once the button has been clicked). To do this I had to select the parent of the parent, since the Remove button is in a div, which is in the div for the whole row of the cart.
The whole loop (including the event listener and the function) looks like this.
for (var i = 0; i < removeCartItemButtons.length; i++) {
var button = removeCartItemButtons[i]
button.addEventListener("click", function(event) {
var buttonClicked = event.target
buttonClicked.parentElement.parentElement.remove()
})
}
I can now remove each item row from my cart, but the total cost is not updating. On to that...
I started by creating a new function called updateCartTotal and called this in the function above. That means, when the loop listening for an event is over (ie the button is clicked), the last thing that gets done is updating the cart total.
We want the updateCartTotal function to:
go through every row in the cart
find the price and quantity on each row
multiply the item price by the quantity to find the row total
sum the row totals together
display total in the total field.
So - and the trainer really rattles along - this is what we do. I will paste the relevant lines of code underneath each subheading and (when I have finished it) will update the are immediately before the next subheading to include all the code together.
function updateCartTotal() {
var cartItemContainer = document.getElementsByClassName("cart-items")[0]
}
We can use the class="cart-items" to getElementsByClassName, since all cart rows are contained in the <div class="cart-items">. Although we need to specify that we only want the first value in this array (since the getElementsByClassName method returns an array). To do this, I added a [0] at the end of the line.
function updateCartTotal() {
var cartItemContainer = document.getElementsByClassName("cart-items")[0]
var cartRows = cartItemContainer.getElementsByClassName("cart-row")
for (var i = 0; i < cartRows.length; i++) {
var cartRow = cartRows[i]
var priceElement = cartRow.getElementsByClassName("cart-price")[0]
var quantityElement = cartRow.getElementsByClassName("cart-quantity-input")[0]
var price = parseFloat(priceElement.innerText.replace("£",""))
var quantity = quantityElement.value
console.log(price * quantity)
}
}
I then used getElementsByClassName again to look for elements with the 'cart-row' class. At all stages, I'm creating Javascript variables which map onto these HTML classes.
I now need to loop through the cart rows looking for the price and quantity of each item. I copied some of the loop code from above and replaced the variable names to match the cart row.
I can now get the HTML elements I need. Now I need to extract the information from them to perform a calculation. In other words, I need to turn...
<span class="cart-price cart-column">£9.99</span>
into a number (9.99) which I can then perform a calculation on. Simple enough, I just called the innerText method on the priceElement, to get the text in the element (in this case £9.99).
I had to remove the pound sign using the replace method and I also had to parse.float to convert the text into a number.
It was easier to get the quantity of each item since this is based on an input (which is a number already). I just created a new variable, which was the quantityElement variable with the value method called on it.
Finally, I added a console to multiply the item cost by the quantity and give me the answer. This was just so I could test my code, I will (presumably) remove this in a later video.
I'm just over 14 minutes in to the Javascript tutorial (though it's taken me way over an hour to get there!). I feel that this is a good place to stop.
I will pick up from here next day.