Creating a Shopping Cart with Vanilla Javascript

Creating a Shopping Cart with Vanilla Javascript

In this article, you'll learn to practice programming a shopping cart using javascript.

Through this topic, I wanna help every people who just a Junior Javascript Developer can have a good document to approach a very fascinating and trending programming language. Now let's start.

Before we start coding we should analyze a bit about why we need to use Vanilla Javascript? Why we do not apply the prominent framework like Reactjs or Angular to make our source code look so nice?

The Reason is Vanilla script with me it is the ancestor of every framework using javascript. So when we are really master the Vanilla Javascript we can very easy to understand the structure of the modern framework and it is a good way to approach faster and deeper with Javascript and easy to extend your knowledge about this one in the future.

Let's move to the coding

Structure of shopping cart project

With Vanilla Script we will direct the CSS and Javascript link in the index.html file.

You can file and copy the source code HTML and CSS in Here: https://github.com/vckhanhitiu1/ShoppingCartWithVanillaJavascript

when we start running the index.html on browser we can see our interface like the image below and we can not interact anything with the website buttons

The Objective of this practice is when we click to the icon below we can add a new course into our list cart.

Now we will move to the app.js file and let start coding

const courses = document.querySelector('#courses-list'),
 shoppingCartContent = document.querySelector('#cart-content tbody')

In the code above, we initialize 2 const value courses and shoppingCartContent .The purpose of them is to get the element which have the id = courses-list

Get Element have id is courses-list

and another one get element tbody inside the table has id is card-content

Get element tbody inside the table has id is card-content

Next, we will write the main function which will be run when the browser is loaded -> we call its name is a listener

loadEventListeners();

function loadEventListeners(){
    //when new course is added
    courses.addEventListener('click', buyCourse);

function buyCourse(e){
    if(e.target.classList.contains('add-to-cart')){
        //read the course value
     const course = e.target.parentElement.parentElement;
        getCourseInfo(course);
    }
}}

The purpose of the code above is when we click to the button which we use *e.target.classList.contains(‘add-to-cart’) *to find the Add To Cart button

when we click to the button Add To Cart we will call the function getCourseInfo()

function getCourseInfo(course) {
    //create an Object with course data
    const courseInfo = {
        image: course.querySelector('img').src,
        title: course.querySelector('h4').textContent,
        price: course.querySelector('.price span').textContent,
        id: course.querySelector('a').getAttribute('data-id')
    }
    addToCart(courseInfo);
}

function addToCart(course){
    const row = document.createElement('tr');

    row.innerHTML = `
<tr>
    <td>
        <img src="${course.image}" width="100">    
    </td>
    <td>
        ${course.title}
    </td>
     <td>
        ${course.price}
    </td>
     <td>
        <a href="#" class="remove" data-id="${course.id}">X</a>
    </td>
</tr>
`
    ;

    shoppingCartContent.appendChild(row);
}

Inside the getCourseInfo(course) function the course value or in this case this is the cart element which we already got when we click to the Add To Cart button

The new value courseInfo will reformat the course element value

We can easily console log to see the courseInfo JSON value

After that, we can call the function addToCart and transfer the courseInfovalue into this function to add the new course information into our cart.

Now let’s move to the addToCart(course)

Inside this course, we will use document.createElement(‘tr’) to create an element in our DOM tree and after that, we will use appendChild() function to add the element into body table of card content.

So the final result when we apply Javascript into our code is when we click the Add To Cart button

And we click to the shopping icon and see the result

Courses can be added after we handle click button with Javascript.

On the same way with add new course online we can implement remove a chose online course by click red button and clear the cart by click CLEAR CART button by follow the code below

shoppingCartContent = document.querySelector('#cart-content tbody'),
clearCartBtn = document.querySelector('#clear-cart');
loadEventListeners();

function loadEventListeners(){
    //when new course is added
    courses.addEventListener('click', buyCourse);
    shoppingCartContent.addEventListener('click', removeCourse);
    clearCartBtn.addEventListener('click', clearCart);
}
function removeCourse(e){
    if(e.target.classList.contains('remove')){
         e.target.parentElement.parentElement.remove();
    }
}

function clearCart(){
    console.log(shoppingCartContent.firstChild)
    while(shoppingCartContent.firstChild){
        shoppingCartContent.removeChild(shoppingCartContent.firstChild);
    }
}

So that all for this topic. Hope that you can learn some new things from my sharing. Enjoy and Keep Learning!

javascript web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.