Code First Girls Logo

A short taster session into the fundamental technologies powering the world wide web.

{{completedPercentage()}}% Complete

Shopping Basket

Okay - it's time to build the first part of our shopping cart. Although there are other parts that are important, by far the most important part of any cart is keeping the running total updated.

When a customer first browses to our little shopping site we want their total basket to be £0.00

When a customer hits one of the "Add to cart" buttons we want the total price to be updated by the correct amount.

Let's start with this.

Running total variable

We'll use a simple variable to store our running total amount. But before we can do this we need to know how to update the value of a variable after it's been set.

What we'll do below is create a variable called total and set it initially to 0. We'll then practise updating this variable by set amounts and print out the running total at each step.

var total = 0; total = total + 10.00 total total = total + 21.55 total

We now know how to store a variable in JavaScript and update it as and when we want.

How we'll do this

We're going to

  • Create a total price variable in our code
  • Add code to our click handlers when users click on the Add to Cart buttons
  • Look up the price of the item when button clicked
  • Add that price to our total variable
  • Update the user display to show the updated total price

Remember $(this)?

Recall that when using click handlers with jQuery, $(this) gets set to the element that we clicked.

Remember $(this).attr()

Recall that you can access an elements attributes using jQuery using $('css selector').attr('attribute name')

You thought that was useless, didn't you! We'll use it now to grab the price of the item that we click on, but first, custom attributes.

HTML Custom Attributes

Although not strictly valid HTML, we can add our own HTML attributes to elements. For instance:

<p custom="myvalue">This is a paragraph</p>
<a href="mylink.html" foo="bar">My Link</a>
<a href="#" price="10.00">Add to basket</a>
Make sure you have your index.html file open in sublime that we created earlier. The one that displays the products. The price shouldn't be 10.00, it should be the price of each of your items

Let's Add!

Okay - let's now add our running total variable into our code. We'll need to be looking at the code in our <script> tag for this part!

This should be the first bit of code inside your <script> tag. See below if you get stuck, but you only need the var total line!
<script>
var total = 0;
function handleClick() {
    ...
}
$(".item").click(handleClick);
// Code will be similar but not exactly the same
</script>

We'll now make our total variable update each time we click on the Add to Basket buttons, but first one more bit of "theory".

Converting Strings to Numbers

Remember that we can have different types of variables: strings and numbers. (There are a few more for the inquisitive amongst you)

var myString = "My name is ...";
var myNumber = 10
var string = "10.00"

In JavaScript, converting between strings and numbers is a common enough task that it has a built in function to do this!

var string = "10.00" string = parseFloat(string)

Okay - let's now use all of this new knowledge to update our total variable when we click a add to basked button.

Remember, var price = $(this).attr('price'); price = parseFloat(price) total = total + price

Displaying the price on our site!

It's not very usefull having a variable held in JavaScript holding the total value of our shopping basket if we can't display it to users. Let's fix this now!

Remember DOM manipulation from the earlier sessions? Thought it was useless, not quite!

Recall that when we created our bootstrap template, we left space for the current value of the basket to be displayed in the header. We'll use this now.

To update the dom with the current total variable's contents. Recall that #total is the span with id="total" and that .text() updates the text of the selected item Veryify that it updates the total price
var total = 0.00;
function handleClick() {
    var price = $(this).attr('price');
    price = parseFloat(price);
    total = total + price
    $('#total').text(total);
}
$('.item').click(handleClick);

What are these decimal points?

In JavaScript a number with decimal places is called a floating point number, and it can (pretty much) have infinite precision. This isn't very useful for our price, as we always only want two decimal places (£10.00, £0.10)

Fortunatly JavaScript comes with a built in tool to help fix exactly this, meet number.toFixed(2).

var myFloat = 10.375825638; var anotherExample = 2848.142583; myFloat.toFixed(2)

We can now use this toFixed(2) method to only ever show two decimal points in our code.

    var total = 0.00;
    function handleClick() {
      var price = $(this).attr('price');
      price = parseFloat(price);
      total = parseFloat(total);
      total = total + price;
      total = total.toFixed(2);
      $('#total').text(total);
    }
    $('.item').click(handleClick);
Note: when you call toFixed() you are turning your number back into a string, so you need to call parseFloat again!

One last thing, we have a small bug. We don't update the total price text on the navigation bar until we add something to the basket. We'll fix this now.

$('#total').text(total)