search
HomeWeb Front-endCSS TutorialMy shopping cart project for a Farm Shop

I've just finished creating a front end shopping cart web app using HTML, CSS & vanilla JavaScript. Because I love buying veg at my local grocers', I based it on a the idea of a farm shop called Finley's Farm Shop.

To click around on the project, the live link is: https://gabrielrowan.github.io/Finleys-Farm-Shop-FE/

My shopping cart project for a Farm Shop

With this app, you can:

? Add shop items to the cart
? Change the quantity of a shop item
? View all the items in the cart on a trolley modal
? See the total price of all items in the cart
? See the number of items in the cart
? Keep all of your items in the cart, even if you refresh the page or close the tab and then reopen it

Background for this project

I've mainly worked on back-end applications in jobs so far. This summer, though, I got to work on a Full-Stack project, including designing and implementing the front-end. I really enjoyed it and it made me want to develop my front end skills more.

I wanted to challenge myself to do this project without using a CSS library, not because I think using them is bad, but because reaching for something like Bootstrap is usually my go-to for the front end.

I'd never used browser local storage with JavaScript before so I decided that creating a project would be the best way for me to learn about it in a practical way.

My Goals for the Project

When I first started this project, I had a few aims in mind. These were:

? Responsiveness - I wanted the UI to adapt to mobile, ipad and desktop views
? To create a shopping cart modal without using a CSS library
? To get familiar with using local storage in JavaScript

Future Goals

Creating the front end is part 1 of my plan for this project. The second part is to turn this into a full-stack app using Django so that the shop items come from a database instead of being hardcoded in the HTML.

Making it responsive

Grid

To make the app adaptable to different screen sizes, I used a version of the responsive grid from this video from Kevin Powell.

The CSS for the

containing the shop item cards from my project is:
.shop-items {
    display: grid;
    gap: 0.6rem;
    grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
}

The magic is in the grid-template-columns value. It essentially means:
Fit as many columns as possible in this parent container with a minimum size of 12rem and a maximum size of 1 fraction of the available space.

Using this grid, the amount of columns (represented by the amount of shop item cards) can dynamically decrease from 4 down to 1 when going from a wider desktop view to the narrower mobile view, without having to write additional media queries.

My shopping cart project for a Farm Shop

Banner Font Size

For the banner title 'Finley's Farm Shop', I used clamp() so that the font size would be able to scale automatically. Without doing this, I found that the font size that worked well for desktop was too big for mobile.

.shop-items {
    display: grid;
    gap: 0.6rem;
    grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
}

This means that the font-size will aim to be 5vw (viewport width - aka 5% of the total visible screen width).

The minimum the font-size can be is 3.8rem, so if 5vw is ever equivalent to less than 3.8rem, then the font-size will be 3.8rem instead.

The maximum the font-size can be is set to 5.6rem, so if 5vw is equivalent to more than 5.6rem then the font-size will be 5.6rem instead.

There are ways of precisely calculating the gradient between your minimum and maximum font size, and using that to choose your preferred middle value, but I eye-balled it using the inspector ?

Here is a CSS Tricks article on working out the exact gradient instead.

Creating the modal

Different Screen Sizes

For the trolley, I wanted a modal that would appear from the right side of the screen on desktop:

My shopping cart project for a Farm Shop

On mobile view, I decided it should take up the full screen size:

My shopping cart project for a Farm Shop

Cart Item Grid Areas

Most of my time was spent on the CSS for the cart item when it has been added to the cart. I used grid-template-areas so that the different parts of the cart item (the item title ie. 'Apple', the price, the item quantity and the image) took up the allocated space that I had planned for them.

My shopping cart project for a Farm Shop

.banner-title {
    font-size: clamp(3.8rem, 5vw, 5.6rem);
}

JavaScript

For the modal javaScript, I was aiming to:

  • Hide the modal when cart icon is clicked
  • Close the modal when the close icon is clicked
  • Disable page scrolling so that it isn't possible to scroll down the main page of shop items when the modal is open

To achieve this, I added event listeners to both icons which called the function toggleModal. This would add a class called .active if it wasn't already added to the modal element, and remove it if it was already there.

In the CSS, I set the modal to be hidden by default, and the .active class was set to display it.

Setting up the CSS:

.shop-items {
    display: grid;
    gap: 0.6rem;
    grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
}

Toggling the class to show/hide the modal:

.banner-title {
    font-size: clamp(3.8rem, 5vw, 5.6rem);
}

This meant that the event listeners on the close icon and the cart icon could reuse the same function, because it would display the modal if it wasn't already displayed and hide it if it was already open.

Using local storage

For local storage, I found this video 'JavaScript Cookies vs. Local Storage vs. Session Storage' from Web Dev Simplified especially helpful. It talks through the differences between these three ways of storing data, how to view the data in the Application tab of dev tools and how to add and remove items for each data storage type.

This is what the Application tab for my project looks like after I've added 2 items to the cart:

My shopping cart project for a Farm Shop

Separation of Concern

I decided to separate out functions that related to modifying the DOM (adding elements, removing elements, editing elements) from functions relating to local storage. For example, I have a function removeCartItemFromLocalStorage which, well, does what it says on the tin and is different to removeCartItemFromModalDOM which removes the shop item html from the modal.

.cart-item {
    display: grid;
    grid-template-areas: "image description description"
        "image price quantity";
    grid-template-columns: min-content 1fr 1fr;
    grid-template-rows: 2.5rem 3.5rem;
}

Both of these need to be called when a shop item is removed from the cart, and having them as separate functions helped me to check off that I'd done both needed parts of the process. Without removing the html from the DOM, the web page wouldn't visually reflect that the item had been deleted from the cart. Without removing the item from local storage, the changes wouldn't be able to persist when the page was refreshed or the tab closed.

Coming across a problem

While I was working on the local storage functions in the JavaScript, I came across a problem that really puzzled me. The steps I'd done so far were:

  • Set local storage to an empty array on initial page load
  • When the 'add' button is clicked on a shop item, these functions are called:
    • Item is added to local storage
    • The HTML for the cart item is added to the trolley modal
  • Retrieve the total price as the quantity * price of every product in the local storage array
  • Set the innerText of the price element to be the price retrieved from local storage

I did some clicking around and it also looked great! ... until I refreshed the page. Then, the price was set to the same total as before, but the DOM had completely reverted to what it looked like on initial page load. Visually, it looked like no items were in the cart (the add button displayed, instead of the quantity input controls), but the total was above £0.

Difference between items added and not added to cart

My shopping cart project for a Farm Shop

This really confused me and took me a while to figure out. Eventually, I got it. Yes, I was adding the items to local storage. But when the page was reloaded and the DOMContentLoaded event listener was fired, I wasn't rendering the DOM based on what was in the local storage. In fact, I wasn't checking what was in local storage at this stage at all.

After I realised this, I created a function called on DOMContentLoaded that looped through all products in the product array in local storage, found the id of each, and then updated the relevant product's html elements to show the ones that had been added to the cart.

A shortened version of the function is:

const loadCartState = () =>
{
    const cart = JSON.parse(localStorage.getItem("cart"));
    if (!cart)
    {
        cart = [];
        localStorage.setItem("cart", JSON.stringify(cart));
    }

    cart.forEach(product =>
    {
         const shopItem = document.querySelector(`.shop-item[data- 
        >



<h2>
  
  
  Deployment
</h2>

<p>I deployed this app using Github Pages. I hadn't used it for deployment before, but found the process very straightforward. The only issue I ran into was that at first none of the images were showing. I realised this was because of case sensitivity: my images folder is called Img but the image paths were img/ in the html. After this was fixed and I cleared my cache, the website displayed as expected. </p>

<h2>
  
  
  Conclusion
</h2>

<p>I learnt a lot from this project, especially about CSS grid and using local storage with JavaScript. I was very tempted to add more pages and turn it into a full front-end ecommerce app, but I've decided to keep it MVP for now so that I can focus on the next stage of making it into a Django app and hooking it up to a database ?</p>


          

The above is the detailed content of My shopping cart project for a Farm Shop. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Adding Box Shadows to WordPress Blocks and ElementsAdding Box Shadows to WordPress Blocks and ElementsMar 09, 2025 pm 12:53 PM

The CSS box-shadow and outline properties gained theme.json support in WordPress 6.1. Let's look at a few examples of how it works in real themes, and what options we have to apply these styles to WordPress blocks and elements.

Working With GraphQL CachingWorking With GraphQL CachingMar 19, 2025 am 09:36 AM

If you’ve recently started working with GraphQL, or reviewed its pros and cons, you’ve no doubt heard things like “GraphQL doesn’t support caching” or

Making Your First Custom Svelte TransitionMaking Your First Custom Svelte TransitionMar 15, 2025 am 11:08 AM

The Svelte transition API provides a way to animate components when they enter or leave the document, including custom Svelte transitions.

Classy and Cool Custom CSS Scrollbars: A ShowcaseClassy and Cool Custom CSS Scrollbars: A ShowcaseMar 10, 2025 am 11:37 AM

In this article we will be diving into the world of scrollbars. I know, it doesn’t sound too glamorous, but trust me, a well-designed page goes hand-in-hand

Show, Don't TellShow, Don't TellMar 16, 2025 am 11:49 AM

How much time do you spend designing the content presentation for your websites? When you write a new blog post or create a new page, are you thinking about

Building an Ethereum app using Redwood.js and FaunaBuilding an Ethereum app using Redwood.js and FaunaMar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

What the Heck Are npm Commands?What the Heck Are npm Commands?Mar 15, 2025 am 11:36 AM

npm commands run various tasks for you, either as a one-off or a continuously running process for things like starting a server or compiling code.

Let's use (X, X, X, X) for talking about specificityLet's use (X, X, X, X) for talking about specificityMar 24, 2025 am 10:37 AM

I was just chatting with Eric Meyer the other day and I remembered an Eric Meyer story from my formative years. I wrote a blog post about CSS specificity, and

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),