Untitled

 avatar
unknown
javascript
a year ago
9.3 kB
12
Indexable
// Variables
const openShopping = document.querySelector('.shopping');
const closeShoppingDiv = document.querySelector('.closeShopping');
const clearCartDiv = document.querySelector('.clearCart');
const list = document.querySelector('.list');
const listCart = document.querySelector('.listCart');
const body = document.querySelector('body');
const total = document.querySelector('.total');
const quantity = document.querySelector('.quantity');

//Product information
const products = [
    { id: 1, name: 'African Milk Tree', image: 'AMT_1.png', images: ['AMT_1.png', 'AMT_2.png', 'AMT_3.png'], price: 79.99, description: 'Euphorbia trigona, the African milk tree, cathedral cactus, or Abyssinian euphorbia, is a species of flowering plant that originates from Central Africa. Somewhat common in cultivation as a houseplant or as a hedge, the species is one of the euphorbias with succulent stems and branches as an adaptation to arid climates.' },
    { id: 2, name: 'Bishop', image: 'Bishop_1.png', images: ['Bishop_1.png', 'Bishop_2.png', 'Bishop_3.png'], price: 69.99, description: 'Astrophytum myriostigma, the bishops cap cactus, bishops hat or bishops miter cactus, is a species of cactus native to the highlands of northeastern and central Mexico.' },
    { id: 3, name: 'Bunny Ears', image: 'Bunny_1.png', images: ['Bunny_1.png', 'Bunny_2.png', 'Bunny_3.png'], price: 129.99, description: 'Opuntia microdasys (angels-wings, bunny ears cactus, bunny cactus or polka-dot cactus) is a species of flowering plant in the cactus family Cactaceae, native and endemic to central and northern Mexico.' },
    { id: 4, name: 'Pincushion', image: 'Pincushion_1.png', images: ['Pincushion_1.png', 'Pincushion_2.png', 'Pincushion_3.png'], price: 149.99, description: 'Pelecyphora, pincushion cactus or foxtail cactus is a genus of cacti, comprising 20 species.They originate from Mexico and the United States. Common species include the Missouri foxtail cactus P. missouriensis, widespread in grassland and forest west of the Mississippi, and the spinystar P. vivipara, distributed across the US and into Canada, first described by Nuttall in 1813.' },
    { id: 5, name: 'Lady Finger', image: 'Lady_1.png', images: ['Lady_1.png', 'Lady_2.png', 'Lady_3.png'], price: 89.99, description: 'Mammillaria elongata, the gold lace cactus or ladyfinger cactus, is a species of flowering plant in the family Cactaceae, native to central Mexico. Growing to 15 cm (6 in) tall by 30 cm (12 in) wide, it consists of densely packed clusters of elongated oval stems, covered in harmless (although very sharp) yellow or brown spines, and in spring producing white or yellow flowers.' },
    { id: 6, name: 'Moon Cactus', image: 'Moon_1.png', images: ['Moon_1.png', 'Moon_2.png', 'Moon_3.png'], price: 49.99, description: 'Gymnocalycium mihanovichii is a species of cactus from South America. The most popular cultivars are varied mutants which completely lack chlorophyll, exposing the red, orange, or yellow pigmentation. These mutant strains are often grafted onto the hylocereus cactus, and the combined plant is called a "Moon Cactus".' }
];

//Makes sure the shopping cart is empty at the start
let cartItems = [];

//Interaction to open the shopping cart
openShopping.addEventListener('click', () => {
    body.classList.add('active');
});

//Interaction to close the shopping cart
closeShoppingDiv.addEventListener('click', () => {
    body.classList.remove('active');
});

//Interaction to clear the shopping cart
clearCartDiv.addEventListener('click', () => {
    cartItems = [];
    updateCart();
});

//Creating products elements to the product list, showing the products on the main page
function runApp() {
    products.forEach((product, index) => {
        let newProduct = document.createElement('div');
        newProduct.classList.add('item');
        newProduct.innerHTML = `
            <img src="image/${product.image}" onclick="openModal(${index})">
            <div class="title">${product.name}</div>
            <div class="price">${formatPrice(parseFloat(product.price))}</div>
            <button onclick="addToCart(${index})">Add To Cart</button>`;
        list.appendChild(newProduct);
    });
}

//Add a product to the cart
function addToCart(index) {
    let product = products[index];
    let existingItem = cartItems.find(item => item.id === product.id);

    if (!existingItem) {
        cartItems.push(Object.assign({}, product, { quantity: 1 }));
    } else {
        existingItem.quantity++;
    }
    updateCart();
}

//Update the shopping cart
function updateCart() {
    listCart.innerHTML = '';
    let totalCount = 0;
    let totalPrice = 0;

    cartItems.forEach(item => {
        totalPrice += item.price;
        totalCount += item.quantity;

        let newProduct = document.createElement('li');
        newProduct.innerHTML = `
            <div><img src="image/${item.image}" alt="${item.name}"></div>
            <div>${item.name}</div>
            <div>${formatPrice(item.price)}</div>
            <div>
                <button onclick="changeQuantity(${item.id}, ${item.quantity - 1})">-</button>
                <div class="count">${item.quantity}</div>
                <button onclick="changeQuantity(${item.id}, ${item.quantity + 1})">+</button>
            </div>`;
        listCart.appendChild(newProduct);
    });
    total.innerText = formatTotalPrice(totalPrice);
    quantity.innerText = totalCount;
}

//Change the quantity of a product in the cart
function changeQuantity(productId, quantity) {
    let item = cartItems.find(item => item.id === productId);

    if (!quantity) {
        cartItems = cartItems.filter(item => item.id !== productId);
    } else {
        item.quantity = quantity;
        item.price = quantity * products.find(product => product.id === productId).price;
    }
    updateCart();
}

//Open the modal with product details
function openModal(index) {
    let product = products[index];
    let modalImage = document.getElementById('modalImage');
    let currentIndex = 0; // Initialize index for the modal image

    //Set the initial image
    modalImage.src = `image/${product.images[currentIndex]}`;
    modalImage.setAttribute('data-current-index', currentIndex);

    //Define the information in the modal
    document.getElementById('modalTitle').innerText = product.name;
    document.getElementById('modalDescription').innerText = product.description;
    document.getElementById('modalPrice').innerText = formatPrice(product.price);
    document.getElementById('productModal').style.display = 'block';
    document.getElementById('quantityValue').innerText = '1';
}

//Close the modal
function closeModal() {
    document.getElementById('productModal').style.display = 'none';
}

//Event listener for closing the modal when clicking outside the modal window
let overlay = document.querySelector('.modal');
overlay.addEventListener('click', (event) => {
    if (!event.target.closest('.modal-content')) {
        closeModal();
    }
});

//Add selected product to the cart from the modal
function addToCartModal() {
    let modalTitle = document.getElementById('modalTitle').innerText;
    let modalPrice = parseFloat(document.getElementById('modalPrice').innerText.replace(' kr', ''));
    let selectedProduct = products.find(product => product.name === modalTitle);

    if (selectedProduct) {
        let quantity = parseInt(document.getElementById('quantityValue').innerText);
        let existingItem = cartItems.find(item => item.id === selectedProduct.id);

        if (!existingItem) {
            cartItems.push(Object.assign({}, selectedProduct, { quantity: quantity, price: modalPrice * quantity }));
        } else {
            existingItem.quantity += quantity;
            existingItem.price += modalPrice * quantity;
        }
        updateCart();
    }
    closeModal();
}

//Function to enable us to scroll through the images in the modal window
function changeImageModal(direction) {
    let modalImage = document.getElementById('modalImage');
    let currentIndex = parseInt(modalImage.getAttribute('data-current-index'));
    let modalTitle = document.getElementById('modalTitle').innerText;
    let product = products.find(product => product.name === modalTitle);

    currentIndex += direction;
    currentIndex = (currentIndex + product.images.length) % product.images.length;

    modalImage.src = `image/${product.images[currentIndex]}`;
    modalImage.setAttribute('data-current-index', currentIndex);
}

//Change the quantity of productgs inside the modal
function changeQuantityModal(change) {
    let quantity = document.getElementById('quantityValue');
    let currentQuantity = parseInt(quantity.innerText);
   
    currentQuantity += change;
    if (currentQuantity < 1) {
        currentQuantity = 1;
    }
    quantity.innerText = currentQuantity;
}

//Formats the price so kr appears after the value
function formatPrice(price) {
    return price.toLocaleString() + ' kr';
}

//Formats the price so kr appears after the total value
function formatTotalPrice(price) {
    return 'Total price: ' + price.toLocaleString() + ' kr';
}

runApp();
Editor is loading...
Leave a Comment