Malfunction detected in JavaScript shopping cart functionality

Trying to implement a functional shopping cart on a webpage has been a challenge for me. I've encountered issues in my JavaScript code that are preventing the cart from working as intended. As a newbie to JavaScript, I'm struggling to pinpoint the exact source of the problem.

The goal was to allow users to add items to the cart and view the total amount, but I'm facing difficulties in getting this functionality to work. While the initial function seemed to be working, subsequent JavaScript additions failed to impact the webpage. I suspect that I may have made a typo or missed some brackets while coding.

For reference, here's the tutorial that I followed:

https://www.youtube.com/watch?v=0I1TorcXFP0&list=PLnHJACx3NwAey1IiiYmxFbXxieMYqnBKF&index=5

The complete code can be found on CodePen at the following link:

https://codepen.io/jlcdevdesign/pen/GRqxBzz

Below is my JavaScript code snippet:

(function() {
const cartInfo = document.getElementById("cart-info");
const cart = document.getElementById("cart");

cartInfo.addEventListener("click", function() {
    cart.classList.toggle("show-cart");
})
})();

      (function(){
 const cartBtn = document.querySelectorAll(".store-item-icon");
 cartBtn.forEach(function(btn){
 btn.addEventListener("click", function(event)){
 
    //console.log(event.target);

    if(event.target.parentElement.classList("store-item-icon"))
    {
       let fullPath = 
       event.target.parentElement.previousElementSibling.src;
       let pos = fullPath.indexOf("img") + 3;
       let partPath = fullPath.slice(pos);

       const item = {};
       item.img = 'img-cart${}partPath';

       let name = event.target.parentElement.parentElement.nextElementSibling.children[0].children[0].textContent;
       item.name = name;
       let price = event.target.parentElement.parentElement.nextElementSibling.children[0].children[1].textContent;

       let finalPrice = price.slice(1).trim();

       item.price = finalPrice;

       const cartItem = document.getElementById('div')
       cartItem.classList.add('cart-item', 'd-flex', 'justify-content-between', 'text-capitalize', 'my-3');

       cartItem.innerHTML = '

       <img src="${item.img}" class="img-fluid rounded-circle" id="item-img" alt="">
       <div class="item-text">

         <p id="cart-item-title" class="font-weight-bold mb-0">${item.name}</p>
         <span>$</span>
    <span id="cart-item-price" class="cart-item-price" class="mb-0">${item.price}</span>
       </div>
       <a href="#" id='cart-item-remove' class="cart-item-remove">
         <i class="fas fa-trash"></i>
       </a>
     </div>
       
       ';
       const cart = deocument.getElementById('cart');
       const total = deocument.querySelector('.cart-total-container');

       cart.insertBefore(cartItem, total);
       alert("item added to the cart");
       showTotals();
    }
 });



 })

 function showTotals() {
     const total = [] {
         const items = document.querySelectorAll(".cart-item-price");

         items.forEach(function(item){
             total.push(parseFloat(item.textContent));
         });
     }
     const totalMoney = total.reduce(function(total,items){
         total += item;
         return total;
     }, 0)
     const finalMoney = totalMoney.toFixed(2);

     document.getElementById('cart-total').textContent = finalMoney;
     document.querySelector('.item-total').textContent = finalMoney;
     document.getElementById('item-count').textContent = total.length;
 }
})();

Answer №1

You made a couple of mistakes in line 53 and 54 where you misspelled 'document' as 'deocument' and forgot to include some braces. Additionally, your code appears to be a bit messy, making it difficult to read. These errors are common for beginners.

I recommend carefully reviewing your code, correcting the spelling errors, and properly placing the braces. This should resolve most of the issues you are facing!

Answer №2

Upon visiting your website, I noticed numerous errors in the code. It seems like you may have just copied and pasted without truly understanding the logic behind it. If you are a beginner or have not completed many projects, I would recommend starting with simpler tasks, such as creating a Rock Paper Scissors game like the one I developed when I first began (simple-rps.vercel.app).

(Note: The links provided are to my past projects and do not require verification.) You can use ctrl + u to view the code, copy it, and paste it into your code editor to add some color coding. Take the time to study the code, understand how it functions, and then attempt to create your own version. Avoid relying on outdated tutorials from two years ago.

Instead, consider following reputable YouTube channels like Programming with Mosh and Online Tutorials for guidance.

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

What sets apart a class from a service in NativeScript?

I am embarking on the journey of learning Nativescript + Angular2, and while reading through the tutorial, I came across this interesting snippet: We’ll build this functionality as an Angular service, which is Angular’s mechanism for reusable classes ...

The functionality of `config.assets.debug = true` fails to

I've encountered an issue with the configuration on development where config.assets.debug = true doesn't seem to work correctly. Instead of having multiple separate JavaScript and CSS file inclusions, I'm getting a consolidated one: <li ...

utilizing jquery ajax for image uploading with php and mysqli

When trying to upload an image URL using AJAX into the database, I encountered an error upon submitting the form. My goal is to upload the image URL into the database without refreshing the page. The specific error message I received was: GET 400 (Bad Re ...

Angular - The argument provided is not compatible with the parameter

I encountered the following TypeScript errors in app.component.ts: Issue: Argument of type '(events: Event[]) => void' is not assignable to parameter of type '(value: Event[]) => void'. Description: Types of parameters 'e ...

Tips for including arrow symbols in your HTML/CSS code and ensuring that they are adaptable to various

I have been working on the following HTML layout using Bootstrap 4, but I've hit a snag with one element. Check out the design preview below: https://i.sstatic.net/V3tzT.png The HTML code is as follows: <section class="hm_sc_1"> < ...

How can I organize a dictionary based on a specified key order in Jinja2?

Suppose I need to showcase the following data: • b is foo • a is bar • c is baz ...however, my dataset is structured like this (or any other sequence due to JSON's flexibility): { "a": "bar", "b": "foo", "c": "baz" } How can I utilize Jinja2 ...

The Cordova imagePickerEx plugin is now also offering a feature to retrieve cached images

When creating a form to upload user data along with multiple images, I am utilizing this plugin. A recurring issue I face is that even after setting "cache view= false", if I select one image, a cached image still appears in the console. <code> var ...

What is causing the button to prevent file selection?

What's causing the button to not allow file selection when clicked on? Interestingly, placing a span or div in the label enables file selection upon clicking them, but not with the button. <html> <body> <label> <input t ...

Creating a NgFor loop in Angular 8 to display a dropdown menu styled using Material

I'm currently facing an issue with incorporating a Materialize dropdown within a dynamically generated table using *ngFor. The dropdown does not display when placed inside the table, however, it works perfectly fine when placed outside. <p>User ...

What is the best method for creating a vertical line separator with a hover effect in CSS?

Facing an issue with creating a vertical line separator in the navigation menu. While trying to add a vertical line separator to my navigation, I noticed that it does not get covered by the hover effect when hovering over the menu items. Please refer to t ...

issue with the load() method

Can someone assist me with the issue I'm encountering regarding the load() function in jQuery? Below is the snippet of code causing problems: $("#addButton").click(function(){ var textbox1 = $("#textbox1").val(); alert(textbox1); $("#sta ...

What are the constraints to consider when working with JSON in a practical setting

I find myself at a pivotal point in my application design process. The project at hand is an ASP.NET web application that utilizes REST to request information on various products. Some of these products have different ProductIDs based on their attributes a ...

Placing <IconButton> at the bottom right of <Paper> using React and Material UI without utilizing FAB

Issue: I'm working on implementing a react/material-ui design where I want to show an edit icon floating in the bottom right corner of a paper element. I've managed to get it to float in the bottom right of the entire screen, but that's not ...

Issue with Node.js Mongoose: Attempting to store a date in UTC Timezone, but it is being saved in the local time

I am relatively new to using nodejs and mongodb. I am encountering an issue with dates while using mongoose for mongodb - whenever I attempt to save a date into the database, it automatically gets converted to the local timezone, which is not the desired b ...

Issue with React event hierarchy

How can I effectively manage state changes in a deep node that also need to be handled by a parent node? Let me explain my scenario: <Table> <Row prop={user1}> <Column prop={user1_col1} /> <Column prop={user1_col2} /> ...

Sass list of Bootstrap version 4 grid dimensions

I'm attempting to integrate Bootstrap v4 variables into my project, which are contained within an array (_variables.scss): $grid-breakpoints: ( xs: 0, sm: 544px, md: 768px, lg: 992px, xl: 1200px ) !default; How can I reference it in my SAS ...

only a single backdrop filter can be in use at any given moment

Experimenting with backdrop-filter in Chrome 76. I'm working on a menu with 2 divs, each with a backdrop-filter applied. The first div is displaying the filter effect perfectly, but the second one isn't. Interestingly, when I remove the filter fr ...

Repurposing React key usage

section, I am curious to know if it is standard practice to reuse a React key from one component to another. For instance, in the Row component, the key obtained from the Column component is reused for mapping the children of Row. const Table = props =& ...

Limiting jQuery datepicker to only show the selected date and disabling all others

I have two datepickers named startdate and enddate. My goal is to restrict all other dates in the enddate datepicker except the selected date from the startdate datepicker. For instance, if I choose 15/12/2016 from the startdate datepicker, I only want the ...

Is there a way to successfully implement this CSS animation utilizing background images in a Markdown document?

I am attempting to create a dynamic animation on a <canvas> element by changing the background image using the @keyframes rule in CSS. Unfortunately, I am facing difficulty getting the animation to work. The <canvas> tag does not even display a ...