w3resource

Build a Shopping Cart using JavaScript and SessionStorage

JavaScript Event Handling: Exercise-17 with Solution

SessionStorage Cart

Write a JavaScript program to simulate a shopping cart where the cart state is stored in sessionStorage.

Solution 1: Basic Shopping Cart with Add and View Functionality

JavaScript Code:

// Initialize the cart from sessionStorage or set it as an empty array
let cart = JSON.parse(sessionStorage.getItem('cart')) || [];

// Function to display the cart
function displayCart() {
  const cartDisplay = document.getElementById('cartDisplay');
  cartDisplay.innerHTML = ''; // Clear previous display

  if (cart.length === 0) {
    cartDisplay.textContent = 'Your cart is empty.';
  } else {
    cart.forEach((item, index) => {
      const itemElement = document.createElement('p'); // Create a paragraph for each item
      itemElement.textContent = `${index + 1}. ${item}`; // Display item with index
      cartDisplay.appendChild(itemElement); // Append to cart display
    });
  }
}

// Create input and buttons for cart actions
const itemInput = document.createElement('input'); // Input for adding items
itemInput.placeholder = 'Enter item name';
document.body.appendChild(itemInput);

const addButton = document.createElement('button'); // Button to add item
addButton.textContent = 'Add to Cart';
document.body.appendChild(addButton);

const cartDisplay = document.createElement('div'); // Div to display the cart
cartDisplay.id = 'cartDisplay';
document.body.appendChild(cartDisplay);

// Display the cart initially
displayCart();

// Add button event listener
addButton.addEventListener('click', () => {
  const newItem = itemInput.value.trim(); // Get item from input
  if (newItem) {
    cart.push(newItem); // Add item to cart
    sessionStorage.setItem('cart', JSON.stringify(cart)); // Save updated cart in sessionStorage
    itemInput.value = ''; // Clear input
    displayCart(); // Update cart display
  } else {
    alert('Please enter an item name.');
  }
});

Output:

Enter item name
Add to Cart
1. Sara
2. Bob
3. Zorica

Explanation:

    1. Cart Initialization:

    • Retrieves the cart state from sessionStorage or initializes it as an empty array.

    2. Cart Display:

    • Displays the cart items dynamically in a div.

    3. Input Field:

    • Provides a text input for adding new items to the cart.

    4. Add to Cart:

    • Adds the entered item to the cart, updates sessionStorage, and refreshes the display.

Solution 2: Shopping Cart with Add, View, and Clear Functionality

JavaScript Code:

// Initialize the cart from sessionStorage or set it as an empty array
let cart = JSON.parse(sessionStorage.getItem('cart')) || [];

// Function to display the cart
function displayCart() {
  const cartDisplay = document.getElementById('cartDisplay');
  cartDisplay.innerHTML = ''; // Clear previous display

  if (cart.length === 0) {
    cartDisplay.textContent = 'Your cart is empty.';
  } else {
    cart.forEach((item, index) => {
      const itemElement = document.createElement('p'); // Create a paragraph for each item
      itemElement.textContent = `${index + 1}. ${item}`; // Display item with index
      cartDisplay.appendChild(itemElement); // Append to cart display
    });
  }
}

// Create input and buttons for cart actions
const itemInput = document.createElement('input'); // Input for adding items
itemInput.placeholder = 'Enter item name';
document.body.appendChild(itemInput);

const addButton = document.createElement('button'); // Button to add item
addButton.textContent = 'Add to Cart';
document.body.appendChild(addButton);

const clearButton = document.createElement('button'); // Button to clear the cart
clearButton.textContent = 'Clear Cart';
document.body.appendChild(clearButton);

const cartDisplay = document.createElement('div'); // Div to display the cart
cartDisplay.id = 'cartDisplay';
document.body.appendChild(cartDisplay);

// Display the cart initially
displayCart();

// Add button event listener
addButton.addEventListener('click', () => {
  const newItem = itemInput.value.trim(); // Get item from input
  if (newItem) {
    cart.push(newItem); // Add item to cart
    sessionStorage.setItem('cart', JSON.stringify(cart)); // Save updated cart in sessionStorage
    itemInput.value = ''; // Clear input
    displayCart(); // Update cart display
  } else {
    alert('Please enter an item name.');
  }
});

// Clear button event listener
clearButton.addEventListener('click', () => {
  cart = []; // Clear the cart array
  sessionStorage.setItem('cart', JSON.stringify(cart)); // Save the empty cart to sessionStorage
  displayCart(); // Update cart display
});

Output:

Enter item name    Add to Cart
Clear Cart

1. Red
2. Green
3. Blue

Explanation:

    1. Cart Initialization:

    • Retrieves the cart state from sessionStorage or initializes it as an empty array.

    2. Cart Display:

    • Dynamically displays the cart items in a div and shows "empty" if the cart is cleared.

    3. Add to Cart:

    • Adds items to the cart, updates sessionStorage, and refreshes the display.

    4. Clear Cart:

    • Clears the cart array, updates sessionStorage with an empty array, and refreshes the display.

Live Demo:

See the Pen javascript-event-handling-exercise-17 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Event Handling Exercises Previous: Creating a Persistent Counter with JavaScript and LocalStorage.
Event Handling Exercises Next: Fetch API and Error Handling in JavaScript.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.