1

I'm currently trying to implement a very simple JS that should take the product name, quantity and price and store it in an json array so I can use it later on as part of the basket abandonment program. I want the data to be stored when someone clicks on the 'Add to Basket' button. Here's the code I have at the moment:

  var basketAllPages = document.getElementsByClassName("action tocart primary");
  var itemListTwo = [];
  var basketOnAddItem = function(){

    $('.minicart-items-wrapper').each(function() {
        var productOnAdd = {
            name: $(this).find('.product-item-name a')[0].innerHTML,
            value: $(this).find('.minicart-price .price')[0].innerHTML.substr(1),
            quantity: $(this).find('.item-qty.cart-item-qty').val()
        };
        console.log(productOnAdd); //to display the product details
        itemListTwo.push(productOnAdd);
        console.log(itemListTwo) // to display an array of products
    })

  };

  for (var i = 0; i < basketAllPages.length; i++) {
      basketAllPages[i].addEventListener('click', basketOnAddItem, false)
  }

It does work to some extent, but there's a small problem I can't figure out how to solve. Basically it works for the 2nd 'add to basket' click onward, but it shows the details of the product added before.

E.g:

  • Add to basket click 1: product name AA, console displays nothing;
  • Add to basket click 2: product name BB, console displays product AA details and prints the array of object AA;
  • Add to basket click 3: product name BB, console displays product BB details and prints and array of objects AA and BB.

I'm guessing it has something to do with the fact that the 'click' event is fired before there're actual products in the basket. I could hack it with the setTimeout() method but that would be very dirty and there's probably a very easy workaround that I'm missing.

Any advice will be much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.