Untitled

 avatar
unknown
plain_text
a year ago
5.7 kB
2
Indexable
class ShoppingCart extends HTMLElement {
  constructor() {
    super();

    // Create a shadow DOM
    this.attachShadow({ mode: 'open' });

    // Set up the initial structure of the component
    this.shadowRoot.innerHTML = `
        <style>
          .items-box {
                width: 300px;
                height: 350px;
                display:flex;
                flex-direction: column;
                
          }
          ul{
            list-style-type: none;
            margin: 15px;
            padding:0;
            
          }
          ul li {
            margin-bottom: 10px;
        }

          header {
            display: flex;
            align-items: center;
            justify-content:center;
          }
          
          h1 {
            font-size: 20px;
            font-weight; bold;
            margin-bottom: 15px;
          }

          p {
            font-size 18px;
            margin-bottom 15px;
          }

          ul button {
            position: absolute;
            right: 0;
            margin-right: 15px;
            margin-top:0px;
            background-color: red;
            color: white;
            padding: 3px 5px;
            border: none;
            border-radius: 2px;
            cursor: pointer;
            font-size: 12px;
            opacity:50%;
            
          }

          footer {
            margin-top: auto;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            
          }
          
          .pay-button {
            background-color: red;
            color: white;
            padding: 10px 20px;
            border: none;
            cursor: pointer;
            font-size: 16px;
            opacity:50%;
            margin-top: auto;
            margin-bottom: 20px;
            
          }
          
          .payment{
            position: absolute;
            background-color:white;
            top:50px;
            left:2px;
            width: 99%;
            height: 80%;
            text-align: center;
          }
         
          .payment p {
            font-weight: bold;
            margin-top: 50px
          }

          img{
            width: 100px;
            height: 100px;
          }

          .hidden{
            display: none;
          }
        </style>
        <div class="items-box">
          <header>
            <h1>Shopping Cart</h1>
          </header>
          <ul id="cart-list"></ul>
          <footer>
            <p>Total: <span id="total-price">0.00</span> kr</p>
            <button class="pay-button">Pay Here</button>
          </footer>
        </div>
        <div class="payment hidden">
           <p>Payment Successful</p>   
           <img src="images/check.png" alt="Background image"> 
        </div>
        
      `;
  }

  connectedCallback() {
    // When the component is connected to the DOM, update the cart
    this.updateCart();
    // Event listener for removing an item from the cart
    this.addEventListener('removeItem', (event) => {
      this.removeItemFromCart(event.detail.itemId);
    });

    this.addEventListener("makePayment", (event) => {
      this.makePayment(event);
    }
    )

  }

  updateCart() {
    let shoppingCart = JSON.parse(localStorage.getItem('shoppingCart')) || [];
    const cartList = this.shadowRoot.getElementById('cart-list');
    const totalPriceElement = this.shadowRoot.getElementById('total-price');
    const payButton = this.shadowRoot.querySelector(".pay-button");
    cartList.innerHTML = ''; // Clear the existing list

    let totalPrice = 0;
    shoppingCart.forEach(cartItem => {
      const li = document.createElement('li');

      // Display item name, quantity, and price
      li.textContent = `${cartItem.name} (Qty: ${cartItem.quantity}) - ${cartItem.quantity * cartItem.price} kr  `;

      // Add a remove button for each item
      const removeButton = document.createElement('button');
      removeButton.textContent = 'Remove';
      removeButton.addEventListener('click', () => {
        this.dispatchEvent(new CustomEvent('removeItem', { detail: { itemId: cartItem.id } }));
      });

      li.appendChild(removeButton);
      cartList.appendChild(li);

      // Update total price
      totalPrice += cartItem.quantity * cartItem.price;
    });

    // Display the total price
    totalPriceElement.textContent = totalPrice;

    payButton.addEventListener('click', () => {
      this.dispatchEvent(new CustomEvent('makePayment'));
    });

  }


  removeItemFromCart(itemId) {
    let shoppingCart = JSON.parse(localStorage.getItem('shoppingCart')) || [];
    const cartItemIndex = shoppingCart.findIndex(cartItem => cartItem.id === itemId);

    if (cartItemIndex !== -1) {
      const cartItem = shoppingCart[cartItemIndex];

      cartItem.quantity = Math.max(cartItem.quantity - 1, 0);

      if (cartItem.quantity === 0) {
        shoppingCart.splice(cartItemIndex, 1);
      }

      localStorage.setItem('shoppingCart', JSON.stringify(shoppingCart));
      this.updateCart();
    }

  }

  //function for payment
  makePayment() {
    let shoppingCart = [];
    localStorage.setItem('shoppingCart', JSON.stringify(shoppingCart));
    const payment = this.shadowRoot.querySelector(".payment");
    payment.classList.remove("hidden");

  }
}

// Define the custom element
customElements.define('shopping-cart', ShoppingCart);
Editor is loading...
Leave a Comment