Using cookies

Treez offers the following guidance on how to implement a cookie-based shopping cart. 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 the HTML structure for the shopping cart

Create a basic HTML structure for displaying cart items.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Shopping Cart</title>
</head>
<body>
    <div id="cart">
        <h2>Shopping Cart</h2>
        <ul id="cart-items">
        </ul>
        <button id="checkout">Checkout</button>
    </div>
</body>
</html>

Create and style the shopping cart using 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 the JavaScript functionality

Begin by creating a JavaScript file to handle the shopping cart functionality. For example, create a file named cart.js and include it in your HTML file:

<script src="cart.js"></script>

In the cart.js file, implement the following functions:

  1. addToCart(item): Adds an item to the cart and updates the cookie.
  2. removeFromCart(itemId): Removes an item from the cart and updates the cookie.
  3. getCartItems(): Retrieves the items in the cart from the cookie.
  4. updateCartDisplay(): Updates the cart's HTML structure based on the current contents of the cart.
  5. init(): Initializes the shopping cart by setting up event listeners and updating the cart display.

For example:

function addToCart(item) {
    // Your implementation here
}

function removeFromCart(itemId) {
    // Your implementation here
}

function getCartItems() {
    // Your implementation here
}

function updateCartDisplay() {
    // Your implementation here
}

function init() {
    // Your implementation here
}

// Initialize the shopping cart
init();

Implement the cookie manipulation functions

In this step, we will create functions to add, remove, and retrieve items from the shopping cart using cookies. These operations will take place in the addToCart(item), removeFromCart(itemId), and getCartItems() functions, respectively.

Adding Items to the Cart

The addToCart(item) function will receive an item object (which might contain properties like id, name, price, etc.), add it to the existing shopping cart items in the cookie, and update the cookie. For simplicity, we will stringify the items array using JSON before storing it in the cookie:

function addToCart(item) {
    let items = getCartItems();

    // Add the new item to the items array
    items.push(item);

    // Update the cookie with the new items array
    let expiryDate = new Date();
    expiryDate.setTime(expiryDate.getTime() + (7 * 24 * 60 * 60 * 1000)); 
    
   // Cookies will expire in 7 days
    document.cookie = `cart=${JSON.stringify(items)};expires=${expiryDate.toUTCString()};path=/`;

    // Update the cart display
    updateCartDisplay();
}

Removing Items from the Cart

The removeFromCart(itemId) function will receive an item ID, remove the corresponding item from the shopping cart items in the cookie, and update the cookie:

function removeFromCart(itemId) {  
    let items = getCartItems();
  
    // Remove the item with the specified ID
    items = items.filter(item => item.id !== itemId);

    // Update the cookie with the new items array
    let expiryDate = new Date();
    expiryDate.setTime(expiryDate.getTime() + (7 * 24 * 60 * 60 * 1000)); // Cookies will expire in 7 days
    document.cookie = `cart=${JSON.stringify(items)};expires=${expiryDate.toUTCString()};path=/`;

    // Update the cart display
    updateCartDisplay();
}

Retrieving Items from the Cart

The getCartItems() function will retrieve the shopping cart items from the cookie and return them as an array:

function getCartItems() {
    // Retrieve the cookie value
    let cookieValue = document.cookie
        .split('; ')
        .find(row => row.startsWith('cart='))
        .split('=')[1];

    // Parse the items from the cookie and return them
    return cookieValue ? JSON.parse(cookieValue) : [];
}

With these functions implemented, your website can now maintain a shopping cart for each user using cookies. Note that this is a very basic implementation and may not be suitable for a large or complex ecommerce website. For example, it does not handle quantities of items, and it does not work well with large numbers of items due to the size limit of cookies.

Remember that the JavaScript document.cookie object is not available in all environments due to security and privacy settings, and its use may be subject to laws and regulations in some jurisdictions. Always ensure that you obtain informed consent from your users before using cookies to store their data. For a more robust and scalable solution, consider using a server-side session or a database to store the shopping cart data.