Why isn't my add to cart button loader functioning correctly?

I implemented ajax cart functionality to add product without reload but in the recommended product coming from cusom collection loader on add to cart work only in first button

here is my code of button

{% render 'loader-image' %} + Add

here is the function call on button click

function showMsg(){
document.querySelector(‘.cart-drawer-loader’).style.display = ‘block’;
document.querySelector(‘.cart-btn-text’).style.opacity = ‘0’;
}

I can’t be able to show the loader in targeted button Any help would be appreciated

Thanks in advance

Hi @Noman-Latif

This is Kate from PageFly - Landing page builder, I’d like to suggest this idea:

You’re facing this issue because you’re using the same class for all the buttons, and therefore, when you change the display property of the element with class .cart-drawer-loader, it affects all the elements with the same class.

A simple solution to this problem is to pass the current button element as an argument to the showMsg function, and then use it to target the specific loader and text associated with that button.

You can consider the code below:


Javascript:

function showMsg(element){
  var loader = element.querySelector('.cart-drawer-loader');
  var text = element.querySelector('.cart-btn-text');

  loader.style.display = 'block';
  text.style.opacity = '0';
}

With this code, the loader and text will only be affected for the button that was clicked, not for all the buttons.

Hope my answer will help you.

1 Like

Hy @PageFly-Kate Thank you for your help it works fine for me