Using local storage

Treez offers the following guidance on how to implement a shopping cart using local browser storage. This is not intended to be a definitive guide, but is designed to provide you with a starting point and reference for your own implementation.

Create HTML Structure

Create a basic HTML structure for displaying cart items.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Shopping Cart</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div id="cart">
        <h2>Shopping Cart</h2>
        <ul id="cart-items">
        </ul>
        <button id="checkout">Checkout</button>
    </div>
    <script src="cart.js"></script>
</body>
</html>

Style with CSS

Save this CSS to style your shopping cart in a file named styles.css

#cart {
    width: 300px;
    background-color: #f8f8f8;
    border: 1px solid #e5e5e5;
    padding: 20px;
}

#cart-items {
    list-style-type: none;
    padding: 0;
    margin: 0;
}

.cart-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #e5e5e5;
}

.cart-item:last-child {
    border-bottom: none;
}

.cart-item-name {
    font-size: 16px;
}

.cart-item-remove {
    color: red;
    cursor: pointer;
}

Implement JavaScript Functions Using Local Storage

In this step, we'll outline the specific functions required to interact with the shopping cart using local storage. The implementation includes initializing the cart, adding items, removing items, and retrieving items.

Initialize Cart Display

Create a function to initialize and render the cart display. This function will be called at the beginning and after any change to the cart.

function initCartDisplay() {
    let items = getCartItems();
    const cartItemsElement = document.getElementById('cart-items');
    cartItemsElement.innerHTML = '';
    
    items.forEach(item => {
        let li = document.createElement('li');
        li.className = 'cart-item';
        li.innerHTML = `<span class="cart-item-name">${item.name}</span>
                        <span class="cart-item-remove" onclick="removeFromCart(${item.id})">Remove</span>`;
        cartItemsElement.appendChild(li);
    });
}

Add Items to Cart

This function takes an item object and adds it to the existing shopping cart items in local storage. It then updates the local storage with the new items array and calls the initCartDisplay() function to refresh the cart display.

function addToCart(item) {
    let items = getCartItems();
    items.push(item);
    localStorage.setItem('cart', JSON.stringify(items));
    initCartDisplay();
}

Here's a sample call to addToCart:

addToCart({id: 1, name: 'Laptop', price: 999});

Remove Items from Cart

When removing items, retrieve the current cart, modify it by filtering out the item with the given ID, and save it back to local storage.

function removeFromCart(itemId) {
    let items = getCartItems();
    items = items.filter(item => item.id !== itemId);
    localStorage.setItem('cart', JSON.stringify(items));
    initCartDisplay();
}

This function is called from the HTML within the initCartDisplay() function.

Retrieve Cart Items

When retrieving cart items, you'll need to parse the JSON string from local storage back into JavaScript objects. If the cart is empty or doesn't exist in local storage, return an empty array.

function getCartItems() {
    let storageValue = localStorage.getItem('cart');
    return storageValue ? JSON.parse(storageValue) : [];
}

Initialize the Shopping Cart

When the page loads, call the initCartDisplay() function to initialize the cart.

// Initialize the shopping cart on page load
initCartDisplay();

Note that these functions can be integrated into a larger JavaScript file, and additional functionality can be added as needed (e.g., adjusting item quantities, applying discounts, etc.). Ensure that local storage is supported in the target browsers and that appropriate error handling is added for a robust implementation.