Simple Shopping List In Vanilla Javascript – Free Source Code

Welcome to a tutorial on how to create a simple shopping list in vanilla Javascript. Nope, I totally did not get the idea for this tutorial from a certain Javascript challenge. It’s original content. 😆 Anyway, a shopping list is totally possible these days with modern Javascript, using the local storage API – That is what we will be using in this guide. Read on to find out!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

TABLE OF CONTENTS

Download & Demo HTML & CSS The Javascript
Useful Bits & Links The End

 

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

SHOPPING LIST DEMO

SHOPPING LIST

ADD ITEM

 

 

HTML & CSS

All right, let us now touch on the landing page for the shopping list itself – The HTML and CSS.

 

THE HTML

shop-list.html
<!-- (A) SHOPPING LIST -->
<h1>SHOPPING LIST</h1>
<div id="shop-list"></div>

<!-- (B) ADD NEW ITEM -->
<h1>ADD ITEM</h1>
<form id="shop-add">
  <input type="text" id="shop-item" placeholder="New Item" required value="1 bag of sugar"/>
  <input type="submit" id="shop-add-btn" value="Add Item"/>
</form>

The HTML is very straightforward, and we only have 2 sections in the interface:

  • At the top is <div id="shop-list"> – We will use Javascript to dynamically generate the shopping list in this empty container.
  • At the bottom is <form id="shop-add"> – Just a simple, single text field HTML form that we will use to add items to the list.

That’s all to the HTML page, the rest of the mechanics will be driven by Javascript.

 

SHOPPING LIST HTML

Just what will be generated by the Javascript into <div id="shop-list">? Here are a few quick dummy entries:

<div id="shop-list">
  <div class="item-row">
    <div class="item-name">1 bag of sugar</div>
    <input type="button" class="item-del" value="Delete"/>
    <input type="button" class="item-ok" value="Got It"/>
  </div>
</div>

 

THE CSS

shop-list.css
/* (A) CONTAINERS + SHARED */
#shop-list, #shop-add {
  display: flex;
  flex-wrap: wrap;
  background: #f2f2f2;
  border: 1px solid #eee;
  padding: 10px;
  max-width: 400px;
}
.item-row, .item-name, .item-del, .item-ok, #shop-item, #shop-add-btn {
  box-sizing: border-box; 
  border: 0;
}
.item-name, #shop-item {
  background: #fff;
  padding: 10px;
}
.item-del, .item-ok, #shop-add-btn {
  cursor: pointer;
  color: #fff;
}

/* (B) SHOPPING LIST */
.item-row {
  display: flex;
  width: 100%;
  margin: 5px 0;
}
.item-name { width: 60%; }
.item-name.item-got { background: #f5fffa; }
.item-name.item-got:before {
  content: "\02713";
  margin-right: 5px;
  font-weight: bold;
  color: #00d036;
}

.item-del, .item-ok { width: 20%; }
.item-del { background: #de1919; }
.item-ok { background: #5a75d6; }

/* (C) ADD ITEM */
#shop-item { width: 75% }
#shop-add-btn {
  width: 25%;
  background: #5a75d6;
}

/* [DOES NOT MATTER] */
html, body { font-family: arial, sans-serif }

Yep, now that you know the HTML layout, the CSS here is just but a few lines of cosmetics. Feel free to spice this one up yourself.

 

 

THE JAVASCRIPT

So far so good? The next part that we will deal with is the main Javascript mechanics itself – Not going to explain line-by-line, but let’s walk through section-by-section.

 

A) SHOPPING LIST INITIALIZATION

shop-list.js
var slist = {
  // (A) INITIALIZE SHOPPING LIST
  items : [], // current shopping list
  hlist : null, // HTML shopping list
  hadd : null, // HTML add item form
  hitem : null, // HTML add item input field
  init : function () {
    // (A1) GET HTML ELEMENTS + "ACTIVATE" ADD ITEM
    slist.hlist = document.getElementById("shop-list");
    slist.hadd = document.getElementById("shop-add");
    slist.hitem = document.getElementById("shop-item");
    slist.hadd.addEventListener("submit", slist.add);

    // (A2) RESTORE PREVIOUS SHOPPING LIST
    if (localStorage.items == undefined) { localStorage.items = "[]"; }
    slist.items = JSON.parse(localStorage.items);

    // (A3) DRAW HTML SHOPPING LIST
    slist.draw();
  }
}
window.addEventListener("DOMContentLoaded", slist.init);
  • Captain Obvious step 1 – var slist is an object that contains all the mechanics for the shopping list.
  • The first thing that we do on page load is to run the slist.init() function to set the list up.
  • What this function does is actually pretty simple –
    • Get all the related HTML elements.
    • Get the saved shopping cart from localstorage.items and restore it into slist.items.
  • Finally, draw the HTML list.

Yep, that’s all. The only important mechanic to take extra here is probably the slist.items array – This is where we save the raw shopping list data and use it to draw the HTML.

 

B) ADD ITEM TO LIST

shop-list.js
var slist = {
  // (B) ADD NEW ITEM TO THE LIST
  add : function (evt) {
    // (B1) PREVENT FORM SUBMIT
    evt.preventDefault();

    // (B2) ADD NEW ITEM TO LIST
    slist.items.push({
      name : slist.hitem.value, // Item name
      done : false // True for "got it", false for not
    });
    slist.hitem.value = "";
    slist.save();

    // (B3) REDRAW HTML SHOPPING LIST
    slist.draw();
  }
};

Moving on, the slist.add() function is fired whenever the user wants to add a new item… This should be pretty self-explanatory:

  • We simply fetch the new item from <input type="text" id="shop-item"/>.
  • Push it into the slist.items array.
  • Also, update the localstorage.

That’s it. But take note of how the slist.items is an array of objects – Every item object has a name and “status” of “got it (true)” or “not yet (false)”.

 

 

C) DRAW SHOPPING LIST HTML

shop-list.js
var slist = {
  // (C) DRAW THE HTML SHOPPING LIST
  draw : function () {
    slist.hlist.innerHTML = "";
    if (slist.items.length > 0) {
      let row, name, delbtn, okbtn;
      for (let i in slist.items) {
        // (C1) ITEM ROW
        row = document.createElement("div");
        row.className = "item-row";
        slist.hlist.appendChild(row);
        
        // (C2) ITEM NAME
        name = document.createElement("div");
        name.className = "item-name";
        name.innerHTML = slist.items[i].name;
        if (slist.items[i].done) {
          name.classList.add("item-got");
        }
        row.appendChild(name);

        // (C3) DELETE BUTTON
        delbtn = document.createElement("input");
        delbtn.className = "item-del";
        delbtn.type = "button";
        delbtn.value = "Delete";
        delbtn.dataset.id = i;
        delbtn.addEventListener("click", slist.delete);
        row.appendChild(delbtn);
        
        // (C4) COMPLETED/NOT YET BUTTON
        okbtn = document.createElement("input");
        okbtn.className = "item-ok";
        okbtn.type = "button";
        okbtn.value = slist.items[i].done ? "Not Yet" : "Got It";
        okbtn.dataset.id = i;
        okbtn.addEventListener("click", slist.toggle);
        row.appendChild(okbtn);
      }
    }
  }
};

Don’t let this slist.draw() function intimidate you. It may look massive, but all it does is to loop through slist.hlist and create the HTML – Which we already went through in the previous section.

 

D) SAVE TO LOCAL STORAGE

shop-list.js
var slist = {
  // (D) SAVE SHOPPING LIST INTO LOCAL STORAGE
  save : function () {
    if (localStorage.items == undefined) { localStorage.items = "[]"; }
    localStorage.items = JSON.stringify(slist.items);
  }
};

No mystery here, just 2 lines of code. The slist.save() fnuction simply saves the slist.items array into the localstorage.

 

 

E) DELETE ITEM

shop-list.js
var slist = {
  // (E) DELETE SELECTED ITEM
  delete : function () {
    if (confirm("Remove selected item?")) {
      slist.items.splice(this.dataset.id, 1); 
      slist.save();
      slist.draw();
    }
  }
};

Yep – This should be self-explanatory as well. Removes an item from slist.items, update the localstorage, then update the HTML.

 

 

F) TOGGLE ITEM STATUS

shop-list.js
var slist = {
  // (F) TOGGLE ITEM BETWEEN "GOT IT" OR "NOT YET"
  toggle : function () {
    let id = this.dataset.id;
    slist.items[id].done = !slist.items[id].done;
    slist.save();
    slist.draw();
  }
};

Finally, this function toggles the “status” of the item between “got it” and “not yet”.

 

USEFUL BITS & LINKS

That’s all for this project, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

1 thought on “Simple Shopping List In Vanilla Javascript – Free Source Code”

Leave a Comment

Your email address will not be published. Required fields are marked *