国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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

My shopping cart project for a Farm Shop

Dec 18, 2024 am 07:27 AM

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How can I include CSS only on some pages? How can I include CSS only on some pages? Jun 11, 2025 am 12:01 AM

There are three ways to selectively include CSS on a specific page: 1. Inline CSS, suitable for pages that are not frequently accessed or require unique styles; 2. Load external CSS files using JavaScript conditions, suitable for situations where flexibility is required; 3. Containment on the server side, suitable for scenarios using server-side languages. This approach can optimize website performance and maintainability, but requires balance of modularity and performance.

Flexbox vs Grid: Understanding the Key Differences in CSS Layout Flexbox vs Grid: Understanding the Key Differences in CSS Layout Jun 10, 2025 am 12:03 AM

Flexboxisidealforone-dimensionallayouts,whileGridsuitstwo-dimensional,complexlayouts.UseFlexboxforaligningitemsinasingleaxisandGridforprecisecontroloverrowsandcolumnsinintricatedesigns.

Creating an Auto-Closing Notification With an HTML Popover Creating an Auto-Closing Notification With an HTML Popover Jun 10, 2025 am 09:45 AM

The HTML popover attribute transforms elements into top-layer elements that can be opened and closed with a button or JavaScript. Popovers can be dismissed a number of ways, but there is no option to auto-close them. Preethi has a technique you can u

What is 'render-blocking CSS'? What is 'render-blocking CSS'? Jun 24, 2025 am 12:42 AM

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

How to use Lotties in Figma How to use Lotties in Figma Jun 14, 2025 am 10:17 AM

In the following tutorial, I will show you how to create Lottie animations in Figma. We'll use two colorful designs to exmplify how you can animate in Figma, and then I'll show you how to go from Figma to Lottie animations. All you need is a free Fig

Breaking Boundaries: Building a Tangram Puzzle With (S)CSS Breaking Boundaries: Building a Tangram Puzzle With (S)CSS Jun 13, 2025 am 11:33 AM

We put it to the test and it turns out Sass can replace JavaScript, at least when it comes to low-level logic and puzzle behavior. With nothing but maps, mixins, functions, and a whole lot of math, we managed to bring our Tangram puzzle to life, no J

External vs. Internal CSS: What's the Best Approach? External vs. Internal CSS: What's the Best Approach? Jun 20, 2025 am 12:45 AM

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

Does my CSS must be on lower case? Does my CSS must be on lower case? Jun 19, 2025 am 12:29 AM

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

See all articles