search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
Create the Product List (HTML)
Manage Cart with JavaScript
Show the Shopping Cart
Home Web Front-end H5 Tutorial How to build a basic shopping cart with HTML5 sessionStorage.

How to build a basic shopping cart with HTML5 sessionStorage.

Dec 22, 2025 am 04:34 AM

首先使用HTML创建商品列表,每个商品包含名称、价格和“添加到购物车”按钮。通过JavaScript的sessionStorage将商品数据以字符串化JSON格式存储,实现页面刷新后数据仍保留。定义addToCart函数向购物车添加商品,内部获取或初始化购物车数组,追加新商品并更新sessionStorage。每次操作后调用updateCart函数,该函数从sessionStorage读取数据并动态生成购物车列表,同时计算总价并更新页面显示。设置clearCart函数用于清空购物车,并在页面加载时调用updateCart恢复购物车状态,确保用户体验连续性。整个方案基于前端技术,无需服务器支持,利用sessionStorage实现会话级数据持久化,关闭浏览器后数据自动清除。

How to build a basic shopping cart with HTML5 sessionStorage.

To build a basic shopping cart using HTML5 sessionStorage, you can store product data as a stringified JSON object. This allows items to persist during the browsing session, even if the page is refreshed. Here's how to set it up simply and effectively.

Create the Product List (HTML)

Start with a simple list of products. Each item needs a name, price, and an "Add to Cart" button.

<div class="product">
  <span>T-Shirt - $20</span>
  <button onclick="addToCart('T-Shirt', 20)">Add to Cart</button>
</div>
<p>&lt;div class="product"&gt;
&lt;span&gt;Jeans - $50&lt;/span&gt;
&lt;button onclick="addToCart('Jeans', 50)"&gt;Add to Cart&lt;/button&gt;
&lt;/div&gt;</p>

Manage Cart with JavaScript

Use JavaScript functions to add items, update the cart display, and save data in sessionStorage.

// Add item to cart
function addToCart(name, price) {
  let cart = JSON.parse(sessionStorage.getItem("cart")) || [];
  cart.push({ name, price });
  sessionStorage.setItem("cart", JSON.stringify(cart));
  updateCart();
}
<p>// Display cart items
function updateCart() {
const cart = JSON.parse(sessionStorage.getItem("cart")) || [];
const cartContainer = document.getElementById("cart-items");
const totalElement = document.getElementById("total");</p><p>cartContainer.innerHTML = ""; // Clear current display</p><p>let total = 0;
cart.forEach(item =&gt; {
total += item.price;
const li = document.createElement("li");
li.textContent = <code>${item.name} - $${item.price}</code>;
cartContainer.appendChild(li);
});</p><p>totalElement.textContent = total;
}</p>

Show the Shopping Cart

Add a section to display the selected items and total cost.

&lt;h2&gt;Your Cart&lt;/h2&gt;
&lt;ul id="cart-items"&gt;&lt;/ul&gt;
&lt;p&gt;Total: $&lt;span id="total"&gt;0&lt;/span&gt;&lt;/p&gt;
&lt;button onclick="clearCart()"&gt;Clear Cart&lt;/button&gt;

You can also include a function to clear the cart:

function clearCart() {
  sessionStorage.removeItem("cart");
  updateCart();
}

Call updateCart() when the page loads to restore the cart from storage:

window.onload = updateCart;

That’s it. You now have a working session-based shopping cart. The data stays only for the current session and clears when the browser closes. No backend needed—just plain HTML, CSS, and JavaScript using sessionStorage. Basically just store, retrieve, and sync the UI.

The above is the detailed content of How to build a basic shopping cart with HTML5 sessionStorage.. 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

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

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)