css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <header class="page-header">
  <!-- The total cart items gets built in the JS, and when > 0, clicking on this brings up the cart modal: -->
  <p class="header-cart"><span class="total-cart-items">0</span> items in cart</p>
</header>

<main class="page-body">
  <section class="products">
    <h1 class="products-title">Products</h1>
    <!-- This is populated by the JS: -->
    <ul class="products-list">
    </ul>
  </section>
</main>

<section class="cart-modal">
  <div class="cart">
    <header class="cart-header">
      <h1 class="cart-title">Cart</h1>
      <p class="cart-close">✖</p>
    </header>
    <!-- The following two elements are populated by the JS -->
    <ul class="cart-items">
    </ul>
    <p class="cart-total"></p>
    <footer class="cart-footer">
      <button class="cart-submit">Submit Order</button>
    </footer>
  </div>
  <div class="cart-submitted">
    <p>Thank you for your order! Give us a few seconds to get it submitted!</p>
  </div>
</section>
            
          
!
            
              body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  text-align: center;
}

button {
  background-color: transparent;
  border: 2px solid currentColor;
  font-weight: bold;
  padding: .75rem;
  text-transform: uppercase;
}

button:active,
button:hover {
  background-color: black;
  color: white;
  font-weight: normal;
}

.page-header {
  border-bottom: 2px solid currentColor;
  display: flex;
  justify-content: flex-end;
  padding: 1rem;
}

.page-body {
  flex: 1;
  display: flex;
}

.products {
  border: 2px solid currentColor;
  margin: auto;
  padding: 1rem;
}

.products-list {
  display: flex;
}

.product {
  display: flex;
  flex: 1;
  flex-direction: column;
  padding: 1rem;
}

.product-description {
  flex: 1;
  font-style: italic;
}

.product-price {
  font-size: 2rem;
  font-weight: bold;
}

.cart-modal {
  background-color: rgba(0, 0, 0, .5);
  display: none;
  position: absolute;
  width: 100vw;
  height: 100vh;
}

.cart-modal.visible {
  display: flex;
}

.cart,
.cart-submitted {
  background-color: white;
  border: 4px solid currentColor;
  border-radius: 1rem;
  margin: auto;
  min-width: 50vw;
  text-align: left;
}

.cart.hidden,
.cart-submitted {
  display: none;
}

.cart-submitted {
  font-size: 1.5rem;
  padding: 1rem;
}

.cart-submitted.visible {
  display: flex;
}


.cart-header,
.cart-items,
.cart-total {
  padding: 0 1rem;
}

.cart-header {
  align-items: center;
  border-bottom: 2px solid currentColor;
  display: flex;
}

.cart-title {
  flex: 1;
}

.cart-close {
  font-size: 2rem;
  line-height: 0;
}

.cart-items {
  list-style-type: none;
  padding: 1rem;
}

.cart-item {
  display: flex;
  margin: 0;
  padding: .5rem 0;
}

.cart-item-name {
  flex: 1;
}

.cart-item-total {
  font-weight: bold;
}

.cart-total {
  border-top: 2px solid currentColor;
  font-weight: bold;
  font-size: 2rem;
  padding: .5rem 1rem;
  text-align: right;
}

.cart-footer {
  padding: .5rem 1rem;
}

.cart-submit {
  width: 100%;
}

            
          
!
            
              // This represents the database, it's a global variable with all the products:
let productData = {
  1: {id: 1, name: "Budget Widget", desc: "If you're cash-strapped, go for this widget. No frills.", price: 5 },
  2: {id: 2, name: "Normal Widget", desc: "Just your common-or-garden widget.", price: 10 },
  3: {id: 3, name: "Super Widget", desc: "Top of the range widget.", price: 20 },
};

// This is the state of the cart, and is a global variable as well (it will get updated)
let cartData = {
  productIds: [],
  totalCost: 0
}

// Given a single product, render a string of HTML:
function renderProduct(productData) {
  const {id, name, desc, price} = productData;
  return `
    <li class="product">
      <h1 class="product-title">${name}</h1>
      <p class="product-description">${desc}</p>
      <p class="product-price">£${price}</p>
      <button class="add-to-cart" data-id=${id}>Add to cart</button>
    </li>
  `;
}

// Given all the producta, map over them and generate the HTML using the previous function:
function renderProducts(productData) {
  document.querySelector('.products-list').innerHTML = Object.values(productData).map(renderProduct).join('');
}

// Rebuild the cartData, adding a product to it. You need to completely overwrite it,
// like so: `cartData = addItemToCart(id, cartData)`
function addItemToCart(id, cartData) {
  return {...cartData, productIds: [...cartData.productIds, id]};
}

// Rebuild the cartData, incrementing the total price. You need to completely overwrite it,
// like so: `cartData = updateTotalPrice(cartData, productData)`
function updateTotalPrice(cartData, productData) {
  const total = cartData.productIds.reduce((acc, id) => acc + productData[id].price, 0);
  return {...cartData, totalCost: total};
}

// Render all the items in the current state of the cart as a set of HTML list items.
function renderCartItems(cartData, productData) {
  const amounts = cartData.productIds.reduce((acc, id) => {
    acc[id] = (id in acc) ? acc[id] + 1 : 1;
    return acc;
  }, {});
 
  return Object.keys(amounts).map(id => {
    const name = `${productData[id].name}${amounts[id] > 1 ? 's' : ''}`;
    const total = amounts[id] * productData[id].price;
    return `
    <li class="cart-item">
      <span class="cart-item-name">${amounts[id]} ${name}: </span>
      <span class="cart-item-total">£${total}</span>
    </li>
    `;
  }).join('');
}

// Render the total price in the current state of the cart as HTML.
function renderCartTotal(cartData, productData) {
  cartData = updateTotalPrice(cartData, productData);
  return `
  <span class="cart-total-prefix">Total: </span>
  <span class="cart-total-price">£${cartData.totalCost}</span>
  `;
}

// Attaches the HTML built in the above functions into the actual HTML page:
function renderCart(cartData, productData) {
  document.querySelector('.cart-items').innerHTML = renderCartItems(cartData, productData);
  document.querySelector('.cart-total').innerHTML = renderCartTotal(cartData, productData);
  document.querySelector('.total-cart-items').innerHTML = cartData.productIds.length;
}

function renderFakeCartSubmission() {
  cartData = { productIds: [], totalCost: 0 };
  document.querySelector('.cart').classList.add('hidden');
  document.querySelector('.cart-submitted').classList.add('visible');
  setTimeout(() => {
    document.querySelector('.cart-modal').classList.remove('visible');
    document.querySelector('.cart').classList.remove('hidden');
    document.querySelector('.cart-submitted').classList.remove('visible');
    document.querySelector('.total-cart-items').innerHTML = cartData.productIds.length;
  }, 2000)
}

// Call render products - this can be built immediately:
renderProducts(productData);

// Click events - adding to the cart, opening the cart modal, and closing it.
document.addEventListener('click', (e) => {
  switch (true) {
    case e.target.classList.contains('add-to-cart'):
      cartData = addItemToCart(e.target.dataset.id, cartData);
      renderCart(cartData, productData);
      break;
    case e.target.classList.contains('header-cart') && cartData.productIds.length > 0:
      document.querySelector('.cart-modal').classList.add('visible');
      break;
    case e.target.classList.contains('cart-close'):
      document.querySelector('.cart-modal').classList.remove('visible');
      break;
    case e.target.classList.contains('cart-submit'):
      renderFakeCartSubmission()
      break;
  }
})
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console