Automatic Cart Refresh

JordanM
Explorer
47 2 6

Hello everyone,

recently i created a store and i wanted to add discounts to products added to cart once the quantity increases. The issue that i faced was that when i change the quantity from 1 to 2 the cart wouldn't refresh and the discount couldn't be seen by the customer. So i managed to create a code that could refresh the cart for every quantity increase.

<script>
var firstChange = true;
function reloadCart(){
var target = document.querySelector(`[data-cart-subtotal]`);

if (!target)return
 
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (firstChange){
    firstChange = false;
    return;
    } else{
      firstChange = true;
    setTimeout(window.location.reload(), 1000);
    }
   
  });    
});
 
var config = { attributes: true, childList: true, characterData: true };
observer.observe(target, config);

}
document.addEventListener("DOMContentLoaded", function() {
 
  reloadCart();
});
 
  selectElements = document.getElementsByClassName(`cart__qty-input`);
 
  var allOne = true;
 
  for (i = 0; i < selectElements.length; i++ ) {
  if (selectElements[i].getAttribute("value") > 1) {
    allOne = false;
         
        }
  }
//   console.log(allOne);
  if (allOne == true) {
    firstChange = false;
  }

</script>

The problem with this code is that it does not work when i add two products which have different colors but are the same type. Then the cart would refresh non-stop

So i tried changing the code with whis:

<script>
var firstChange = true;
function reloadCart(){
var target = document.querySelector(`[data-cart-subtotal]`);

if (!target)return
 
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (firstChange){
    firstChange = false;
    return;
    } else{
      firstChange = true;
    setTimeout(window.location.reload(), 1000);
    }
   
  });    
});
 
var config = { attributes: true, childList: true, characterData: true };
observer.observe(target, config);

}
document.addEventListener("DOMContentLoaded", function() {
 
  reloadCart();
});
 
  selectElements = document.getElementsByClassId(`cart__qty-input`);
 
  var allOne = true;
 
  for (i = 0; i < selectElements.length; i++ ) {
  if (selectElements[i].getAttribute("value") > 1) {
    allOne = false;
         
        }
  }
//   console.log(allOne);
  if (allOne == true) {
    firstChange = false;
  }

</script>

 Now i select elements by class ID and not class Name

Now the code does not work when there is only one product in the cart. It does not refresh the cart when i change from quantity 1 to 2. However it works perfectly when there are more then one products added with different colors to the cart.

I wonder how i can make one piece of code that would work in both circumstances without an issue

Thanks in advance!

0 Likes