Home > Web Front-end > CSS Tutorial > My shopping cart project for a Farm Shop

My shopping cart project for a Farm Shop

Susan Sarandon
Release: 2024-12-18 07:27:09
Original
552 people have browsed it

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));
}
Copy after login
Copy after login
Copy after login

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));
}
Copy after login
Copy after login
Copy after login

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);
}

Copy after login
Copy after login

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));
}
Copy after login
Copy after login
Copy after login

Toggling the class to show/hide the modal:

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

Copy after login
Copy after login

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;
}

Copy after login

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>


          

            
        
Copy after login

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!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template