How to prevent / delay from cart drawer to open?

Harelk1015
Shopify Partner
27 1 1

Hi,
Im creating an app and i want to show a modal after user clicked the add to cart button, and if he clicks agree on the modal only then i want all the add to cart funcionality to run.

I mean if the user approved then i want the cart drawer to open or what ever cart modal there is, and i want it to work on any shop, doesnt matter which cart drawer it has, and ofcurse i want it to add the product to the cart.

 

Please help 🙂

Reply 1 (1)

Harelk1015
Shopify Partner
27 1 1
document.addEventListener("DOMContentLoaded", () => {
  document.addEventListener(
    "submit",
    async (event) => {
      const isAddToCartForm = event.target.action && event.target.action.endsWith("/cart/add");
      if (isAddToCartForm) {
        event.preventDefault(); // Prevents the default form submission
        event.stopPropagation(); // Stops the event from propagating to parent elements

        console.log(event.target);
        // Confirmation dialog
        const userConfirmed = confirm("Are you sure you want to add this item to your cart?");
        if (userConfirmed) {
          // If the user clicks "OK", manually submit the form or handle the add to cart functionality here.
          // You might need to trigger Shopify's AJAX API for adding to cart or submit the form programmatically like:
          // event.target.submit();

          await fetch("/cart/add", {
            method: "post",
            body: new FormData(event.target),
          });

          // document.getElementById("cart-notification").classList.add("active");
          document.querySelector('cart-drawer').classList.add('active');
        } else {
          // If the user clicks "Cancel", just show an alert or handle accordingly.
          alert("Item was not added to your cart.");
        }
      }
    },
    true
  ); // Use capturing phase to ensure this runs before Shopify's own scripts
});

I have added this code, it manages to stop the cart action, but when i run the fetch /cart/add it does add the product to the cart but it doesnt live update the quantity or open the drawer