JavaScript code that displays items in a shopping cart

I've set up the HTML and JS functionality for the cart, but I'm facing an issue where the JS doesn't render the cart items when the shop item is clicked. The styling in my HTML is done using Tailwind.

If anyone could provide some assistance with this, it would be greatly appreciated!

Code snippet:

function ready() {
    // Code snippet goes here
}

// Other functions go here

ready();
<!DOCTYPE html>
<html>
    <head>
        <title>My Store</title>
        <meta name="description" content="This is the description">
        <link rel="stylesheet" href="styles.css" />
        <script src="store.js" async></script>
    </head>
    <body>
        <header class="main-header">
            // Header section goes here
        </header>
        // Other sections of the HTML page go here
    </body>
</html>

Answer №1

<!DOCTYPE html>
<html>
    <head>
        <title>The Generics | Online Shop</title>
        <meta name="description" content="Welcome to our online store">
        
    </head>
    <body>
        <header class="main-header">
            <nav class="main-nav nav">
                <ul>
                    <li><a href="index.html">HOME</a></li>
                    <li><a href="store.html">SHOP</a></li>
                    <li><a href="about.html">ABOUT</a></li>
                </ul>
            </nav>
            <h1 class="band-name band-name-large">The Generics</h1>
        </header>
        <section class="container content-section">
            <h2 class="section-header">MUSIC</h2>
            <div class="shop-items">
                <div class="shop-item">
                    <span class="shop-item-title">Album 1</span>
                    <img class="shop-item-image" src="Images/Album 1.png">
                    <div class="shop-item-details">
                        <span class="shop-item-price">$12.99</span>
                        <button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
                    </div>
                </div>
                <div class="shop-item">
                    <span class="shop-item-title">Album 2</span>
                    <img class="shop-item-image" src="Images/Album 2.png">
                    <div class="shop-item-details">
                        <span class="shop-item-price">$14.99</span>
                        <button class="btn btn-primary shop-item-button"type="button">ADD TO CART</button>
                    </div>
                </div>
                <div class="shop-item">
                    <span class="shop-item-title">Album 3</span>
                    <img class="shop-item-image" src="Images/Album 3.png">
                    <div class="shop-item-details">
                        <span class="shop-item-price">$9.99</span>
                        <button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
                    </div>
                </div>
                <div class="shop-item">
                    <span class="shop-item-title">Album 4</span>
                    <img class="shop-item-image" src="Images/Album 4.png">
                    <div class="shop-item-details">
                        <span class="shop-item-price">$19.99</span>
                        <button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
                    </div>
                </div>
            </div>
        </section>
        <section class="container content-section">
            <h2 class="section-header">MERCHANDISE</h2>
            <div class="shop-items">
                <div class="shop-item">
                    <span class="shop-item-title">T-Shirt</span>
                    <img class="shop-item-image" src="Images/Shirt.png">
                    <div class="shop-item-details">
                        <span class="shop-item-price">$19.99</span>
                        <button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
                    </div>
                </div>
                <div class="shop-item">
                    <span class="shop-item-title">Coffee Cup</span>
                    <img class="shop-item-image" src="Images/Coffee.png">
                    <div class="shop-item-details">
                        <span class="shop-item-price">$6.99</span>
                        <button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
                    </div>
                </div>
            </div>
        </section>
        <footer class="main-footer">
            <div class="container main-footer-container">
                <h3 class="band-name">The Generics</h3>
                <ul class="nav footer-nav">
                    <li>
                        <a href="https://www.youtube.com" target="_blank">
                            <img src="Images/YouTube Logo.png">
                        </a>
                    </li>
                    <li>
                        <a href="https://www.spotify.com" target="_blank">
                            <img src="Images/Spotify Logo.png">
                        </a>
                    </li>
                    <li>
                        <a href="https://www.facebook.com" target="_blank">
                            <img src="Images/Facebook Logo.png">
                        </a>
                    </li>
                </ul>
            </div>
        </footer>
        <script>
            function ready() {
            let removeCartItemButtons = document.getElementsByClassName('btn-danger');
            for (let i = 0; i < removeCartItemButtons.length; i++) {
                let button = removeCartItemButtons[i];
                button.addEventListener('click', removeCartItem);
            }

            let quantityInputs = document.getElementsByClassName('cart-quantity-input');
            for (let i = 0; i < quantityInputs.length; i++) {
                let input = quantityInputs[i];
                input.addEventListener('change', quantityChanged);
            }

            let addToCartButtons = document.getElementsByClassName('shop-item-button');
            for (let i = 0; i < addToCartButtons.length; i++) {
                let button = addToCartButtons[i];
                button.addEventListener('click', addToCartClicked);
            }

            document.getElementsByClassName('btn-purchase')[0].addEventListener('click', purchaseClicked);
        }

        function purchaseClicked() {
            alert('Thank you for shopping with us!');
            let cartItems = document.getElementsByClassName('.cart-items')[0];
            while (cartItems.hasChildNodes()) {
                cartItems.removeChild(cartItems.firstChild);
            }
            updateCartTotal();
        }

        function removeCartItem(event) {
            let buttonClicked = event.target;
            buttonClicked.parentElement.parentElement.remove();
            updateCartTotal();
        }

        function quantityChanged(event) {
            let input = event.target;
            if (isNaN(input.value) || input.value <= 0) {
                input.value = 1;
            }
            updateCartTotal();
        }

        function addToCartClicked(event) {
            let button = event.target;
            let shopItem = button.parentElement.parentElement;
            let title = shopItem.getElementsByClassName('shop-item-title')[0].innerText;
            let price = shopItem.getElementsByClassName('shop-item-price')[0].innerText;
            let imageSrc = shopItem.getElementsByClassName('shop-item-image')[0].src;
            addItemToCart(title, price, imageSrc);
            updateCartTotal();
        }

        function addItemToCart(title, price, imageSrc) {
            let cartRow = document.createElement('div');
            cartRow.classList.add('cart-row');
            let cartItems = document.getElementsByClassName('cart-items')[0];
            let cartItemNames = cartItems.getElementsByClassName('cart-item-title');
            for (let i = 0; i < cartItemNames.length; i++) {
                if (cartItemNames[i].innerText == title) {
                    alert('This item is already in your cart');
                    return
                };
            };
            let cartRowContents = `
                <div class="grid align-middle grid-cols-3 gap-2 my-4">
                        <img class="h-28 w-28" src="${imageSrc}" alt="Product"/>
                            <div>
                                <h4>${price}</h4>
                                <h5 class="cart-price">${price}</h5>
                                <span class="text-red-200 cursor-pointer remove-btn">Remove</span>
                            </div>
                            <div>
                                <input class="cart-quantity-input" type="number" value="1">
                    <button class="btn btn-danger" type="button">REMOVE</button>
                            </div>
                        </div>`;
            cartRow.innerHTML = cartRowContents;
            cartItems.append(cartRow);
            cartRow.getElementsByClassName('btn-danger')[0].addEventListener('click', removeCartItem);
            cartRow.getElementsByClassName('cart-quantity-input')[0].addEventListener('change', quantityChanged);
        }

        function updateCartTotal() {
            let cartItemContainer = document.getElementsByClassName('cart-items')[0];
            let cartRows = cartItemContainer.getElementsByClassName('cart-row');
            let total = 0;
            for (let i = 0; i < cartRows.length; i++) {
                let cartRow = cartRows[i];
                let priceElement = cartRow.getElementsByClassName('cart-price')[0];
                let quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0];
                let price = parseFloat(priceElement.innerText.replace('$', ''));
                let quantity = quantityElement.value;
                total = total + (price * quantity);
            }
            total = Math.round(total * 100) / 100;
            document.getElementsByClassName('cart-total-price')[0].innerText = '$' + total;
        }

        ready();
        </script>
    </body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking to incorporate multiple accordion drop down menus on your website? Utilize a combination of HTML, CSS, and JavaScript to

I am experiencing a challenge with implementing multiple accordion menus on my website. Whenever I attempt to duplicate the code, the new accordion menu appears but clicking on the first bar simply scrolls me back to the top of the webpage. Below is the H ...

Choose a Range of DOM Elements

My challenge is to select a range of DOM elements, starting from element until element. This can be done in jQuery like this: (Source) $('#id').nextUntil('#id2').andSelf().add('#id2') I want to achieve the same using JavaScr ...

"Node.js is giving an error stating that the object does not have a

I am attempting to save the user details from the registration form into a JSON file for authentication purposes. However, I am having trouble appending the data in the correct format. Here is the code snippet that I have tried: var filename = "./user_log ...

I am encountering an issue with Angular where the following error message is displayed: "src/app/app.component.html:18:20 - error TS2339: Property 'DepScreen' does not exist on type 'AppComponent'"

This code snippet is from my app.component.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" ...

Adjusting the height of a card in Reactstrap

I am currently exploring Reactstrap and aiming to ensure a specific Card adjusts according to the size of the window by setting its aspect ratio using percentages rather than pixels. Interestingly, while adjusting the width works as desired, I'm faci ...

Warning: The use of 'node --inspect --debug-brk' is outdated and no longer recommended

Encountering this error for the first time, please forgive any oversight on my part. The complete error message I am receiving when running my code is: (node:10812) [DEP0062] DeprecationWarning: `node --inspect --debug-brk` is deprecated. Please use `node ...

Upon submission in Vue, the data variable becomes undefined

I set isError to false in the data, but when there is an error from Laravel, I receive a 422 error. I want to then set isError to true, but when I do, I get an error in the console saying that isError is undefined even though it has been defined. What coul ...

Utilizing the Command Line/Window feature within Visual Studio Code

As a newcomer to Visual Studio Code, I'm currently using the latest Version: 1.29.1. When I used Matlab, I had access to a script window for writing code, a Command Window for testing code snippets and viewing variable values, as well as a workspace ...

Discrepancy in Code Outputs

Last night, I spent some time testing out code for basic functions. To preview my work, I used two platforms - Dash and JSFiddle. Everything seemed to be running smoothly on both sites. However, when I uploaded the code to my live website, none of the butt ...

Repeating the process of duplicating with jQuery and inserting after each clone multiple times

Attempting to showcase a dynamic form for my business partner. The aim is to add select elements when the button is clicked, but currently encountering an issue where it duplicates the template twice instead of just once. Experimented with different code ...

Utilizing a variable in a for loop with Django

I am a beginner in the world of Python and Django framework and I am encountering a small hurdle when trying to assign a variable to my for loop. Within my html file, there are buttons and a list (generated through a loop). For example: Buttons <li&g ...

The HTML component fails to acknowledge width settings

I seem to be having trouble identifying an issue or perhaps I am misunderstanding something (I am using daisyui + nx + tailwind css + angular). To simplify my problem, let's consider the following scenarios: In the first scenario, I have: <div cl ...

Error in background request for Chrome app/extension, or problem allowing app to access Google Docs API

I'm encountering an issue where the Google Doc API is not allowing a desktop application to be installed, although this worked fine in Chrome 27.0 previously. Below is my Manifest.Json file: { "name": "__MSG_extName__", "description": "__MSG_ext ...

Is there a way to keep my fixed footer container from moving while zooming in and out on a webpage

Is there a way to prevent the bottom text from shifting when zoomed in or out on the page? The rest of the content remains stable, but due to using position:absolute for this section to stay at the bottom of another div (content), it causes movement. #con ...

Middleware that is commonly used by both error handling and regular request-response chains

I am currently working on implementing a middleware that can set a variable in the sequence of both error and non-error scenarios. Is there a way to achieve this without disrupting the normal flow of middleware? Specifically, when I include the err param ...

Is there a way to gather selected checkboxes from all child checkbox components in vue?

I have a unique setup where my table rows are generated by child components, each containing a checkbox. I am looking for a way to retrieve all the checked checkboxes at once without using two-way binding or updating an array on the parent component. Here ...

What is the best way to duplicate an entire webpage with all its content intact?

Is it possible to copy an entire page including images and CSS using Selenium? Traditional methods like ctrl + a or dragging the mouse over the page do not seem to work. How can this be achieved with Selenium without requiring an element to interact with? ...

What is the best way to set a parent element's width to be the same as one of

Is it possible to make the width of div.main match that of table.tbl2? In this scenario, I want inline4 to be on the second line and for the width of div.main to be identical to the width of table.tbl2. .container { text-align: center; } .main { di ...

Generate a text input field within a dropdown menu

Below is an example of my basic HTML code for a drop-down list: <span id="Div_List"> <label for="Gender">For:</label> <select name="Gender" id="Sex"> <option value="1">1000mtr</option> <option val ...

Having trouble with jQuery UI draggable when using jQueryUI version 1.12.1?

Currently, I am diving into the world of jQuery UI. However, I am facing an issue with dragging the boxes that I have created using a combination of HTML and CSS. My setup includes HTML5 and CSS3 alongside jQuery version 1.12.1. Any suggestions or help wou ...