Code First Girls Logo

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

{{completedPercentage()}}% Complete

Displaying the Shopping Basket

In this session we'll build that page of our site that will display the shopping basket. It's awesome that we can add up the total price of goods in our basket, but not so useful if we can't see what we're buying!

But unfortunately before we can build that, we do need yet another little bit of theory!

A page for your basket

Recall that when we created our index.html page we created a link to the basket.html page - the page that will display the contents of the basket. Let's create this now.

This must be in the same folder as your index.html file! Copy everything from the DOCTYPE, html and head into your new file Look below for details, it should have a <span> tag inside that too!

You should have a HTML skeleton that looks similar to:

<DOCTYPE html>
<html>
    <head>
    ... everything from index.html
    </head>
    <body>
        <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
            ...
        </div>
        <h1>Total: £<span id="basket_total">0.00</span></h1>
    </body>
    <script>
    </script>
</html>

Using our total variable

Now - you may be thinking this will be an easy task. We have our total variable, right? We can just update the DOM to display the contents of our var total.

Maybe you're thinking you could use code like: $("#basket_total").text(total).

Whilst that's sensible to think, unfortunately it's not that easy.

When we browse away from our index.html file we "lose" access to our total variable. We can only use that when we are on the page on which it is set.

Cookies?

I'm sure many of you may have heard of cookies, but maybe you're not quite sure what they are. Cookies are small files that live in the browser that can hold a small amount of data. Cookies persist over page loads, so they would have been perfect for storing the total value of our shopping basket in.

Before HTML5 came along, if we'd have wanted to store some data accross our entire site we'd would have used cookies, now however we have an alternative: localStorage

Local Storage

localStorage is a modern alternative to storing data in cookies. localStorage allows us to store things in key value pairs.

These key value pairs allow us to store something and give it a name, and then retrieve it later.

An example:

localStorage.setItem("total", 10.00)
localStorage.setItem("name", "My Name")
var total = localStorage.getItem("total")
var name = localStorage.getItem("name")

To store something with a name in localStorage we use localStorage.setItem("name", "value").

To later retrieve that name we use: localStorage.getItem("name")

localStorage.setItem("name", "Your name") You should be able to see all of your stored local data localStorage.getItem("name") Note how this persists even though we closed the tab!

Storing the total price in localStorage

Okay - we know understand what localStorage is. We can use it to store the total basket value. We can update the localStorage value every time it changes and then retrieve it on the basket page.

See below. Add this to the click handler function.
    total = total + price;
    localStorage.setItem('total', total);

This creates a key in our localStorage with a name of total and a value of the current basket total.

We also need to set the initial value of our total variable be equal to the current stored value. This ensures we don't reset total to 0.00 each time we load the page.

The weird syntax below || means OR. If nothing is found in localStorage we then set the initial value to 0.00.

    var total = 0.00; // old code
    var total = localStorage.getItem('total') || 0; // new code
This sets the initial value of total to be the currently stored value

Adding total to our basket page

Now that we have our total variable stored in localStorage we can access it on our basket.html page.

var total = localStorage.getItem("total"); $('#total').text(total); $('#basket_total').text(total)

Objects in JavaScript

Objects, commonly called dictionaries or hashes are a fundamental data type in JavaScript and other programming languages.

Much like the name dictionary would suggest, objects are key value pairs of data. The dictionary analogy taken a little further: A dictionary of words and definitions could be considered a key value pair, where the key in each case is the word and the value is the description. This is how you make a dictionary in JavaScript

{
    dog: "a common animal with four legs, especially kept by people as a pet or to hunt or guard things",
    cat: "a small animal with fur, four legs, a tail, and claws, usually kept as a pet or for catching mice"
}

In general, we use the syntax:

{
    name: 'value',
    another_nae: 'another value',
    foo: 'bar'
}
var item = { title: 'Product title', price: '10.00'} item.title & item.price

What's this got to do with anything?

The way our shopping cart with work:

  • Creates an array to store the basket items in
  • Every time Add to Button is clicked create a dictionary representing the item
  • Push that dictionary into the array of basket items
  • Store this array in localStorage
  • When the basket.html page is visited
  • Retrieve the basket items out of localStorage
  • Use jQuery .append() to create a new HTML tag forEach element in the basket items array. Display this on the basket.html page

Much like how we added a custom attribute to our Add to Basket buttons for the price, we'll now do the same for title.

<a price="10.00" title="JS Book>"

The open ended end

Believe it or not, you now have enough knowledge to build this simple shopping cart. It's obviously in need of some critical features before we could publish it online, but it's a good start.

Below you will find the code that adds the extra features in. You should study the code to see what it is doing before adding it to your site.

index.html <script> tag:
    var total = localStorage.getItem('total') || 0.00;
    var items = JSON.parse(localStorage.getItem('items')) || [];

    function handleClick() {
      var price = parseFloat($(this).attr('price'));
      var title = $(this).attr('title');
      total = parseFloat(total);
      total = total + price;
      total = total.toFixed(2);
      localStorage.setItem('total', total);
      items.push({title: title, price: price});
      localStorage.setItem('items', JSON.stringify(items));
      $('#total').text(total);
    }

    $('.item').click(handleClick);
    $('#total').text(total)
basket.html <script> tag
    var total = localStorage.getItem("total");
    $('#total').text(total);
    $('#basket_total').text(total);
    var items = JSON.parse(localStorage.getItem('items')) || [];
    items.forEach(function(item) {
      $('#items').append('<li>' + item.title + '</li>')
    })
Try and make sense of it! You may need to do some googling! Some of these lines are new, add them to your index.html and basket.html file <ul id="items"> It should be left empty!