Problem with executing JavaScript function

Hi guys,

I’m working on a typical e-commerce platform and I’ve created a function to add items to the cart whenever a user clicks on a button. Once an item is added, the button gets disabled and the text changes from ‘add to cart’ to ‘in cart’.

The problem that I’m facing is that sometimes when I click on a button, it doesn’t get disabled and also the text doesn’t get updated but the item is still added to the cart. It happens sporadically and completely randomly. I tried to search for some patterns but I can’t find any and have no idea what could be a reason of that. Any ideas? Basically it looks like once in a while the function is skipping the first step on random products but I have no idea how it happens.

The function has the following steps:

  1. User clicks on a button.
  2. The text of a button changes and the button gets disabled.
  3. Searches for the relevant item in a local storage and adds it to a cart.
  4. Updates local storage etc.

The function:

 button.addEventListener("click",(event) => {
       = "In Cart";
       = true;
               // get the product and also add the amount
                let cartItem = {...Storage.getProduct(id), amount: 1}; 

                // add product to the cart 
                cart = [...cart, cartItem];

                // save the cart in the local storage

                // set cart values

                // display cart item
                // check if the cart is empty or not


Thank you as usual!

I don’t do a lot of this. but this looks odd to me, modifying the event object. I would expect you to either modify the button or to access it though some kind of “this”.

1 Like

Does the button have any other elements inside of it? If so, then if they click the button and the mouse is over one of those elements then the target will actually be that element and not the button.

Just a guess since I can’t see it, but I’ve been bit by that before.


Thank you! Yes, now I realised that it happens when I click on a little bag icon inside the button. But I was sure this was part of the button as it is inside the button tag. I’m a bit confused now. Did you find any solution for that?

<button class="bag-btn" data-id=${}>
                <img src="./assets/images/icons8-bag-48.png" />add

Since the handler is on the button you can use event.currentTarget which will always point to the button regardless of what element was actually clicked on.

1 Like

Thank you so much :blush: I was thinking of creating some pseudo elements in CSS but that solved my problem way quicker!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.