How to make the Cart Drawer work with Add to cart button in EComposer?

Author: An Do 3822 views

Cart Drawer is a feature that allows customers to view and manage their shopping cart from any page on your store. This can be useful for customers who want to keep track of their shopping progress, or for stores that want to encourage customers to complete their purchases. 

Note: You can only do this when your theme has the cart drawer function and when the pages in EComposer have Shopify Header enabled.

First, you need to install the Ajax cart extension and select the action to Show a cart popup for the Add to cart button on your product page. The Ajax cart extension is available on the paid plans only.

Then, you need to add some custom code below to the Custom js code box in the Site Settings tab of EComposer. Don’t forget to click the Save settings button to save the changes.

Note: The Cart drawer will make your page reload after the customer clicks on the Add to cart button and then open the Cart sidebar.

1. With Kalles (version 4.x or older), Unsen, Ocolus, and Gecko (version 6.x) themes of The4

You can find the Kalles and Unsen theme on Themeforest.

The code below is for Kalles (version 4.x or older), Unsen, and Gecko (version 6.x) theme:

document.addEventListener("DOMContentLoaded", function () {
  setTimeout(function () {
    if (window.EComposer) {
      window.EComposer.ajaxCartSuccess = function (data, form) {
        document.dispatchEvent(new CustomEvent("cart:refresh:opend"));
      };
    }
  }, 1500);
});

2. With the Debutify theme

You can download the Debutify theme here

document.addEventListener("DOMContentLoaded", function () {
setTimeout(function() {
  if(window.EComposer && window.ajaxCart && window.ajaxCart.load){
      EComposer.ajaxCartSuccess = function(data,f){
        ajaxCart.load();
      }
  }
}, 1000)
});

3. With the Origin theme of Shopify

You can download the Origin theme here

document.addEventListener("DOMContentLoaded", function () {

  setTimeout(function () {

    if (window.EComposer) {

      window.EComposer.ajaxCartSuccess = function (data, form) {

        const cart = document.querySelector("cart-notification") || document.querySelector("cart-drawer");

        const cartItems = document.querySelector("cart-drawer-items");

        document.querySelector("cart-drawer") && document.querySelector("cart-drawer").classList.remove('is-empty');

        fetch(${routes.cart_url}?section_id=main-cart-items)

          .then((response) => response.text())

          .then((responseText) => {

            const html = new DOMParser().parseFromString(responseText, "text/html");

            const sourceQty = html.querySelector("cart-items");

            cartItems.innerHTML = sourceQty.innerHTML;

            cart.renderContents(data);

          })

          .catch((e) => {

            console.error(e);

          });

      };

    }

  }, 500);

});

4. With the Umino theme

You can download the Umino theme here


document.addEventListener('DOMContentLoaded', function() {
    setTimeout(function() {
        if(window.EComposer){
            const cart = document.querySelector('cart-notification');
            EComposer.ajaxCartSuccess = function(data,f){
                if(cart) {
                    fetch(`/?sections=form-mini-cart`)
                    .then((res) => res.text())
                    .then((res) => {
                        const t = JSON.parse(res);
                        data.sections = t;
                        cart.getSectionsToRender().forEach((e) => {
                            const n = document.getElementById(e.id),
                                o = new DOMParser().parseFromString(data.sections[e.id], "text/html");
                            n.innerHTML = o.querySelector("#form-mini-cart").innerHTML;
                            const i = cart.querySelector(".cart-countdown-time"),
                                s = o.querySelector(".cart-countdown-time");
                            i && s && ((i.innerHTML = s.innerHTML), cart.countdownTimer());
                        })
                        cart.cartAction();
                        cart.open();
                        cart && cart.classList.contains("is-empty") && cart.classList.remove("is-empty"),
                        Shopify.termsConditionsAction(),
                        BlsLazyloadImg.init();
                        fetch('/cart.json')
                        .then((res) => res.json())
                        .then((res) => {
                            document.querySelectorAll(".cart-count").forEach((t) => {
                                t.innerHTML = res.item_count;
                            })
                        })
                        
                    })
                }

            }
        }
    }, 2000)
})

5. With the Dawn theme of Shopify

/* DAWN */

document.addEventListener("DOMContentLoaded", function () {

  setTimeout(function () {

    if (window.EComposer) {

      window.EComposer.ajaxCartSuccess = function (data, form) {

        const cart = document.querySelector("cart-notification") || document.querySelector("cart-drawer");

        if (cart) {

          cart.renderContents(data);

        cart.classList.remove('is-empty');

        }

      };

    }

  }, 1000);

});

If the above code doesn’t work, you can try the below code:

document.addEventListener("DOMContentLoaded", function () {
	setTimeout(function () {
		let cart = document.querySelector("cart-drawer");
		let sections = ['cart-drawer', 'cart-icon-bubble'];
		if (window.EComposer && cart) {
			window.EComposer.handleClickEvent = function (btn, event, list = false) {
				event.preventDefault();
				const wrapper = btn.closest('.ecom-collection__product-form__actions');
				let quantity = 1;
				let el_quantity = null;
				if(wrapper){
					el_quantity = wrapper.querySelector('.ecom-collection__product-quantity-input');
				}
				if(el_quantity){
					quantity = el_quantity.value;
				}
				const submitButton = btn,
					_this = window.EComposer;
				if (submitButton) {
					submitButton.style.cursor = "pointer";
					submitButton.style.pointerEvents = "auto";
					submitButton.classList.add("ecom-ajax-loading");
				}
				_this.beforeAjaxCartSend(event.target);
				window
					.fetch(_this.routes.cart_add_url, {
						method: "POST",
						headers: {
							Accept: "application/json",
							"Content-Type": "application/json",
						},
						body: JSON.stringify({
							id: submitButton.dataset.id,
							quantity: quantity,
							sections: sections
						}),
					})
					.then((res) => res.json())
					.then((response) => {
						if (response.errors) {
							throw new Error(response.errors);
						}
						let { action, href, textAddedCart, target, messageAddedCart } =
							submitButton.dataset;
						if (submitButton) {
							submitButton.style.cursor = "pointer";
							submitButton.style.pointerEvents = "auto";
							submitButton.classList.remove(
								"ecom-ajax-loading",
								"ecom-loading"
							);
							submitButton.querySelector(
								".ecom-add-to-cart-text"
							).innerHTML = textAddedCart;
						}
						if (_this.onAjaxCartSuccess) {
							_this.onAjaxCartSuccess(response, event.target);
						}
		
						if (list && !_this.configs.ajax_cart.enable) {
							return setTimeout(function () {
								return (window.location.href = _this.routes.cart_url);
							}, 500);
						}
						switch (action) {
							case "cart":
								return setTimeout(function () {
									return (window.location.href =
										_this.routes.cart_url);
								}, 500);
							case "reload":
								return setTimeout(function () {
									return window.location.reload();
								}, 500);
							case "checkout":
								return setTimeout(function () {
									return (window.location.href =
										_this.routes.root_url + "checkout");
								}, 500);
							case "message":
								_this.showToast(messageAddedCart);
								break;
							case "link":
								if (href) {
									return setTimeout(function () {
										if (target === "_blank") {
											return window.open(href);
										} else {
											return (window.location.href = href);
										}
									}, 500);
								}
							default:
								_this.ajaxCartSuccess(response, event.target);
								break;
						}
					})
					.catch((e) => {
						window.alert(e.message);
						console.error(e);
						if (submitButton) {
							submitButton.style.cursor = "pointer";
							submitButton.style.pointerEvents = "auto";
							submitButton.classList.remove(
								"ecom-ajax-loading",
								"ecom-loading"
							);
						}
						_this.ajaxCartError(e, event.target);
					});
			};
			EComposer.ajaxCartSuccess = function (data, f) {
				cart.classList.remove('is-empty');
				cart.renderContents(data);
			};

		}
	}, 2000);
});

Or this code:

/* DAWN */

document.addEventListener("DOMContentLoaded", function () {

  setTimeout(function () {

    if (window.EComposer) {

      window.EComposer.ajaxCartSuccess = function (data, form) {

        const cart = document.querySelector("cart-notification") || document.querySelector("cart-drawer");

        if (cart) {

          cart.renderContents(data);

        cart.classList.remove('is-empty');

        }

      };

      EComposer.handleClickEvent = function (btn, event, list = false) {
        event.preventDefault();
        const wrapper = btn.closest('.ecom-collection__product-form__actions');
        let quantity = 1;
        let el_quantity = null;
        if(wrapper){
            el_quantity = wrapper.querySelector('.ecom-collection__product-quantity-input');
        }
        if(el_quantity){
            quantity = el_quantity.value;
        }
        const submitButton = btn,
            _this = EComposer;
        if (submitButton) {
            submitButton.style.cursor = "pointer";
            submitButton.style.pointerEvents = "auto";
            submitButton.classList.add("ecom-ajax-loading");
        }
        _this.beforeAjaxCartSend(event.target);
        window
            .fetch(_this.routes.cart_add_url, {
                method: "POST",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    id: submitButton.dataset.id,
                    quantity: quantity,
                    sections: "cart-notification-product,cart-notification-button,cart-icon-bubble,cart-drawer"
                }),
            })
            .then((res) => res.json())
            .then((response) => {
                if (response.errors) {
                    throw new Error(response.errors);
                }
                let { action, href, textAddedCart, target, messageAddedCart } =
                    submitButton.dataset;
                if (submitButton) {
                    submitButton.style.cursor = "pointer";
                    submitButton.style.pointerEvents = "auto";
                    submitButton.classList.remove(
                        "ecom-ajax-loading",
                        "ecom-loading"
                    );
                    submitButton.querySelector(
                        ".ecom-add-to-cart-text"
                    ).innerHTML = textAddedCart;
                }
                if (_this.onAjaxCartSuccess) {
                    _this.onAjaxCartSuccess(response, event.target);
                }

                if (list && !_this.configs.ajax_cart.enable) {
                    return setTimeout(function () {
                        return (window.location.href = _this.routes.cart_url);
                    }, 500);
                }
                switch (action) {
                    case "cart":
                        return setTimeout(function () {
                            return (window.location.href =
                                _this.routes.cart_url);
                        }, 500);
                    case "reload":
                        return setTimeout(function () {
                            return window.location.reload();
                        }, 500);
                    case "checkout":
                        return setTimeout(function () {
                            return (window.location.href =
                                _this.routes.root_url + "checkout");
                        }, 500);
                    case "message":
                        _this.showToast(messageAddedCart);
                        break;
                    case "link":
                        if (href) {
                            return setTimeout(function () {
                                if (target === "_blank") {
                                    return window.open(href);
                                } else {
                                    return (window.location.href = href);
                                }
                            }, 500);
                        }
                    default:
                        _this.ajaxCartSuccess(response, event.target);
                        break;
                }
            })
            .catch((e) => {
                window.alert(e.message);
                console.error(e);
                if (submitButton) {
                    submitButton.style.cursor = "pointer";
                    submitButton.style.pointerEvents = "auto";
                    submitButton.classList.remove(
                        "ecom-ajax-loading",
                        "ecom-loading"
                    );
                }
                _this.ajaxCartError(e, event.target);
            });
    };

    }

  }, 1000);

});

6. With the December theme of Shopify

document.addEventListener("DOMContentLoaded", function () {

  setTimeout(function () {

    if (window.EComposer) {

      window.EComposer.ajaxCartSuccess = function (data, form) {

        setTimeout(function() {
            theme.miniCart.updateElements();
            theme.miniCart.generateCart();
        }, 200)

      };

    }

  }, 500);

});

7. With the Sense theme of Shopify

document.addEventListener("DOMContentLoaded", function () {
  setTimeout(function () {
    if (window.EComposer) {
      window.EComposer.ajaxCartSuccess = function (data, form) {
        const cart = document.querySelector("cart-notification") || document.querySelector("cart-drawer");
        const cartItems = document.querySelector("cart-drawer-items");
        document.querySelector("cart-drawer") && document.querySelector("cart-drawer").classList.remove("is-empty");
        fetch(`${routes.cart_url}?section_id=main-cart-items`)
          .then((response) => response.text())
          .then((responseText) => {
            const html = new DOMParser().parseFromString(responseText, "text/html");
            const sourceQty = html.querySelector("cart-items");
            cartItems.innerHTML = sourceQty.innerHTML;
            cart.renderContents(data);
          })
          .catch((e) => {
            console.error(e);
          });
      };
    }
  }, 1500);
});

or this code if a problems happen

document.addEventListener("DOMContentLoaded", function () {

  setTimeout(function () {

    if (window.EComposer && window.routes) {

      window.EComposer.ajaxCartSuccess = function (data, form) {

        const cart = document.querySelector("cart-notification") || document.querySelector("cart-drawer");

        const cartItems = document.querySelector("cart-drawer-items");

        document.querySelector("cart-drawer") && document.querySelector("cart-drawer").classList.remove("is-empty");

        fetch(${routes.cart_url}?section_id=main-cart-items)

          .then((response) => response.text())

          .then((responseText) => {

            const html = new DOMParser().parseFromString(responseText, "text/html");

            const sourceQty = html.querySelector("cart-items");

            cartItems.innerHTML = sourceQty.innerHTML;

            cart.renderContents(data);

          })

          .catch((e) => {

            console.error(e);

          });

      };

    }

  }, 1500);

});

8. With the Upscale theme

You can download the theme here

document.addEventListener("DOMContentLoaded", function () {
    setTimeout(function () {
      if (window.EComposer) {
        const btn = document.querySelector("#HeaderCartIcon button");
        let cart =
          document.querySelector("loess-cart-notification") ||
          document.querySelector("loess-cart-drawer-items");
        function getSectionsToRender() {
          return [
            {
              id: "MainCartItems",
              section: "cart-drawer-items",
              selector: ".cart-items",
            },
            {
              id: "HeaderCartIcon",
              section: "header-cart-icon",
              selector: ".shopify-section",
            },
            {
              id: "FreeShippingText",
              section: "free-shipping-text",
              selector: ".shopify-section",
            },
            {
              id: "CartDrawerTotalPrice",
              section: "cart-total-price",
              selector: ".shopify-section",
            },
          ];
        }
        let sections = getSectionsToRender().map((section) => section.section);
        window.EComposer.ajaxCart = function () {
            var _this = window.EComposer;
            var handleEvent = (event) => {
                event.preventDefault();
                if (!event.target.querySelector('[name="id"]')) {
                    if (window.document.querySelector("#admin-bar-iframe")) {
                        alert(
                            'Please drag Variant picker element to this section to allow the "Add to cart" feature working. This message only show for owner\'s store'
                        );
                        return false;
                    } else {
                        return false;
                    }
                }
                var submitButton = event.target.querySelector(
                    ".ecom-product-single__add-to-cart--submit.ecom-clicked"
                );
                if(!submitButton) {
                    submitButton = event.target.querySelector(
                        ".ecom-product-single__add-to-cart--submit"
                    );
                }
    
                if (submitButton) {
                    submitButton.style.cursor = "not-allowed";
                    submitButton.style.pointerEvents = "none";
                    submitButton.classList.add("ecom-ajax-loading", "ecom-loading");
                }
                _this.beforeAjaxCartSend(event.target);
                let formData = new FormData(event.target);
                //Params to open cart draw dawn theme
                formData.append(
                    "sections",
                    sections
                );
                window
                    .fetch(_this.routes.cart_add_url, {
                        method: "POST",
                        headers: {
                            Accept: "application/json",
                        },
                        body: formData,
                    })
                    .then((res) => res.json())
                    .then((response) => {
                        if (response.errors) {
                            throw new Error(response.errors);
                        }
                        let {
                            action,
                            href,
                            textAddedCart,
                            target,
                            messageAddedCart,
                        } = submitButton.dataset;
                        if (submitButton) {
                            submitButton.style.cursor = "pointer";
                            submitButton.style.pointerEvents = "auto";
                            submitButton.classList.remove(
                                "ecom-ajax-loading",
                                "ecom-loading"
                            );
                            if (
                                submitButton.querySelector(".ecom-add-to-cart-text")
                            ) {
                                submitButton.querySelector(
                                    ".ecom-add-to-cart-text"
                                ).innerHTML = textAddedCart;
                            }
                        }
                        if (_this.onAjaxCartSuccess) {
                            _this.onAjaxCartSuccess(response, event.target);
                        }
                        let routes = _this.routes;
                        switch (action) {
                            case "cart":
                                return setTimeout(function () {
                                    window.location.href = routes.cart_url;
                                }, 500);
                            case "reload":
                                return setTimeout(function () {
                                    return window.location.reload();
                                }, 500);
    
                            case "checkout":
                                return setTimeout(function () {
                                    return (window.location.href =
                                        routes.root_url +
                                        (routes.root_url === "/" ? "" : "/") +
                                        "checkout");
                                }, 500);
                            case "message":
                                _this.showToast(messageAddedCart);
                                break;
                            case "link":
                                if (href) {
                                    setTimeout(function () {
                                        if (target === "_blank") {
                                            return window.open(href);
                                        } else {
                                            return (window.location.href = href);
                                        }
                                    }, 500);
                                }
                            default:
                                _this.ajaxCartSuccess(response, event.target);
                                break;
                        }
                    })
                    .catch((e) => {
                        if (submitButton) {
                            submitButton.style.cursor = "pointer";
                            submitButton.style.pointerEvents = "auto";
                            submitButton.classList.remove(
                                "ecom-ajax-loading",
                                "ecom-loading"
                            );
                        }
                        _this.ajaxCartError(e, event.target);
                    });
                return false;
            };
    
            //Handle ATC single product
            const submitButtons = document.querySelectorAll(
                ".ecom-product-single__add-to-cart--submit"
            );
            if(submitButtons.length) {
                submitButtons.forEach(function(btn) {
                    btn.addEventListener('click', function() {
                        submitButtons.forEach(function(b) {
                            b.classList.remove('ecom-clicked');
                        })
                        btn.classList.add('ecom-clicked');
                    })
                });
            }
    
            document.body.addEventListener("submit", function (e) {
                if (
                    e.target.classList.contains("ecom-product-form") &&
                    e.target.nodeName === "FORM"
                ) {
                    e.preventDefault();
                    e.stopPropagation();
                    handleEvent.bind(this)(e);
                    return false;
                }
            });
            _this.handleATCList();
            let $elements = document.querySelectorAll(
                ".ecom-ajax-cart-simple[data-id]"
            );
            $elements.forEach(function ($element) {
                $element.addEventListener("click", function (e) {
                    _this.handleClickEvent(this, e);
                });
            });
        };
        window.EComposer.ajaxCart();
        EComposer.ajaxCartSuccess = function (data, f) {
            if(data.sections['cart-drawer-items']) {
                cart.renderCartItems(data);
                setTimeout(() => {
                  document
                    .querySelector(
                      `[aria-controls="${cart.closest("loess-drawer").id}"`
                    )
                    .click();
                }, 100);
            }
            else return;
        };
      }
    }, 1000);
  });
  

If the above code doesn’t work, please try this code:

document.addEventListener('DOMContentLoaded', function() {
  setTimeout(function () {
    if (window.EComposer) {
      window.EComposer.ajaxCartSuccess = function (data, form) {
        const cart = document.querySelector("loess-drawer#CartDrawer");
        const cartItems = cart.querySelector("loess-cart-drawer-items");
        fetch(`/?sections=cart-drawer-items,cart-total-price,free-shipping-text,header-cart-icon`)
        .then((res) => res.json())
        .then((response) => {
          data.sections = response;
          cartItems.renderCartItems(data);
          setTimeout(() => {
              document.querySelector(`[aria-controls="${cartItems.closest('loess-drawer').id}"`).click();
          }, 100);
        });
      };
  
    }
  }, 1000);
})

9. With the Enterprise theme

You can download the theme here

document.addEventListener("DOMContentLoaded", function () {
    setTimeout(function () {
      if (window.EComposer) {
        const cart =
          document.querySelector("cart-notification") ||
          document.querySelector("cart-drawer");
        let sections = "cart-icon-bubble";
        sections += `,${cart
          .closest(".shopify-section")
          .id.replace("shopify-section-", "")}`;
        let sectionTheme = `${cart
          .closest(".shopify-section")
          .id.replace("shopify-section-", "")}`;
        window.EComposer.ajaxCart = function () {
          var _this = window.EComposer;
          var handleEvent = (event) => {
            event.preventDefault();
            if (!event.target.querySelector('[name="id"]')) {
              if (window.document.querySelector("#admin-bar-iframe")) {
                alert(
                  'Please drag Variant picker element to this section to allow the "Add to cart" feature working. This message only show for owner\'s store'
                );
                return false;
              } else {
                return false;
              }
            }
            var submitButton = event.target.querySelector(
              ".ecom-product-single__add-to-cart--submit"
            );
            if (!submitButton) {
              submitButton = event.target.querySelector(
                ".ecom-product-single__add-to-cart--submit"
              );
            }
            if (submitButton) {
              submitButton.style.cursor = "not-allowed";
              submitButton.style.pointerEvents = "none";
              submitButton.classList.add("ecom-ajax-loading", "ecom-loading");
            }
            this.beforeAjaxCartSend(event.target);
            let formData = new FormData(event.target);
            //Params to open cart draw dawn theme
            formData.append(
              "sections",
              `cart-notification-product,cart-notification-button,cart-icon-bubble,cart-drawer,${sectionTheme}`
            );
            window
              .fetch(this.routes.cart_add_url, {
                method: "POST",
                headers: {
                  Accept: "application/json",
                },
                body: formData,
              })
              .then((res) => res.json())
              .then((response) => {
                if (response.errors) {
                  throw new Error(response.errors);
                }
                let { action, href, textAddedCart, target, messageAddedCart } =
                  submitButton.dataset;
                if (submitButton) {
                  submitButton.style.cursor = "pointer";
                  submitButton.style.pointerEvents = "auto";
                  submitButton.classList.remove(
                    "ecom-ajax-loading",
                    "ecom-loading"
                  );
                  if (submitButton.querySelector(".ecom-add-to-cart-text")) {
                    submitButton.querySelector(
                      ".ecom-add-to-cart-text"
                    ).innerHTML = textAddedCart;
                  }
                }
                if (this.onAjaxCartSuccess) {
                  this.onAjaxCartSuccess(response, event.target);
                }
                let routes = this.routes;
                switch (action) {
                  case "cart":
                    return setTimeout(function () {
                      window.location.href = routes.cart_url;
                    }, 500);
                  case "reload":
                    return setTimeout(function () {
                      return window.location.reload();
                    }, 500);
  
                  case "checkout":
                    return setTimeout(function () {
                      return (window.location.href =
                        routes.root_url +
                        (routes.root_url === "/" ? "" : "/") +
                        "checkout");
                    }, 500);
                  case "message":
                    this.showToast(messageAddedCart);
                    break;
                  case "link":
                    if (href) {
                      setTimeout(function () {
                        if (target === "_blank") {
                          return window.open(href);
                        } else {
                          return (window.location.href = href);
                        }
                      }, 500);
                    }
                  default:
                    this.ajaxCartSuccess(response, event.target);
                    break;
                }
              })
              .catch((e) => {
                if (submitButton) {
                  submitButton.style.cursor = "pointer";
                  submitButton.style.pointerEvents = "auto";
                  submitButton.classList.remove(
                    "ecom-ajax-loading",
                    "ecom-loading"
                  );
                }
                this.ajaxCartError(e, event.target);
              });
            return false;
          };
  
          //Handle ATC single product
          const submitButtons = document.querySelectorAll(
            ".ecom-product-single__add-to-cart--submit"
          );
          if (submitButtons.length) {
            submitButtons.forEach(function (btn) {
              btn.addEventListener("click", function () {
                submitButtons.forEach(function (b) {
                  b.classList.remove("ecom-clicked");
                });
                btn.classList.add("ecom-clicked");
              });
            });
          }
  
          document.body.addEventListener("submit", function (e) {
            if (
              e.target.classList.contains("ecom-product-form") &&
              e.target.nodeName === "FORM"
            ) {
              e.preventDefault();
              handleEvent.bind(this)(e);
              return false;
            }
          });
          this.handleATCList();
          let $elements = document.querySelectorAll(
            ".ecom-ajax-cart-simple[data-id]"
          );
          var _this = window.EComposer;
          $elements.forEach(function ($element) {
            $element.addEventListener("click", function (e) {
              _this.handleClickEvent(this, e);
            });
          });
        };
        window.EComposer.ajaxCart();
        window.EComposer.handleClickEvent = function (btn, event, list = false) {
          event.preventDefault();
          const wrapper = btn.closest(".ecom-collection__product-form__actions");
          let quantity = 1;
          let el_quantity = null;
          if (wrapper) {
            el_quantity = wrapper.querySelector(
              ".ecom-collection__product-quantity-input"
            );
          }
          if (el_quantity) {
            quantity = el_quantity.value;
          }
          const submitButton = btn,
            _this = EComposer;
          if (submitButton) {
            submitButton.style.cursor = "pointer";
            submitButton.style.pointerEvents = "auto";
            submitButton.classList.add("ecom-ajax-loading");
          }
          _this.beforeAjaxCartSend(event.target);
          window
            .fetch(_this.routes.cart_add_url, {
              method: "POST",
              headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                id: submitButton.dataset.id,
                quantity: quantity,
                sections: sections,
              }),
            })
            .then((res) => res.json())
            .then((response) => {
              if (response.errors) {
                throw new Error(response.errors);
              }
              let { action, href, textAddedCart, target, messageAddedCart } =
                submitButton.dataset;
              if (submitButton) {
                submitButton.style.cursor = "pointer";
                submitButton.style.pointerEvents = "auto";
                submitButton.classList.remove(
                  "ecom-ajax-loading",
                  "ecom-loading"
                );
                submitButton.querySelector(".ecom-add-to-cart-text").innerHTML =
                  textAddedCart;
              }
              if (_this.onAjaxCartSuccess) {
                _this.onAjaxCartSuccess(response, event.target);
              }
  
              if (list && !_this.configs.ajax_cart.enable) {
                return setTimeout(function () {
                  return (window.location.href = _this.routes.cart_url);
                }, 500);
              }
              switch (action) {
                case "cart":
                  return setTimeout(function () {
                    return (window.location.href = _this.routes.cart_url);
                  }, 500);
                case "reload":
                  return setTimeout(function () {
                    return window.location.reload();
                  }, 500);
                case "checkout":
                  return setTimeout(function () {
                    return (window.location.href =
                      _this.routes.root_url + "checkout");
                  }, 500);
                case "message":
                  _this.showToast(messageAddedCart);
                  break;
                case "link":
                  if (href) {
                    return setTimeout(function () {
                      if (target === "_blank") {
                        return window.open(href);
                      } else {
                        return (window.location.href = href);
                      }
                    }, 500);
                  }
                default:
                  _this.ajaxCartSuccess(response, event.target);
                  break;
              }
            })
            .catch((e) => {
              window.alert(e.message);
              console.error(e);
              if (submitButton) {
                submitButton.style.cursor = "pointer";
                submitButton.style.pointerEvents = "auto";
                submitButton.classList.remove(
                  "ecom-ajax-loading",
                  "ecom-loading"
                );
              }
              _this.ajaxCartError(e, event.target);
            });
        };
        window.EComposer.ajaxCartSuccess = function (data, form) {
          const cart =
            document.querySelector("cart-notification") ||
            document.querySelector("cart-drawer");
          if (cart) {
            cart.renderContents(data);
          }
        };
      }
    }, 1000);
  });
  

10. With the Stiletto theme

document.addEventListener("DOMContentLoaded", function () {
	setTimeout(function () {
		let cart = document.querySelector(".quick-cart__wrapper");
		let sections = ['cart-drawer', 'cart-icon-bubble'];
		if (window.EComposer && cart) {
			window.EComposer.handleClickEvent = function (btn, event, list = false) {
				event.preventDefault();
				event.stopPropagation();
				const wrapper = btn.closest('.ecom-collection__product-form__actions');
				let quantity = 1;
				let el_quantity = null;
				if(wrapper){
					el_quantity = wrapper.querySelector('.ecom-collection__product-quantity-input');
				}
				if(el_quantity){
					quantity = el_quantity.value;
				}
				const submitButton = btn,
					_this = window.EComposer;
				if (submitButton) {
					submitButton.style.cursor = "pointer";
					submitButton.style.pointerEvents = "auto";
					submitButton.classList.add("ecom-ajax-loading");
				}
				_this.beforeAjaxCartSend(event.target);
				window
					.fetch(_this.routes.cart_add_url, {
						method: "POST",
						headers: {
							Accept: "application/json",
							"Content-Type": "application/json",
						},
						body: JSON.stringify({
							id: submitButton.dataset.id,
							quantity: quantity,
							sections: sections
						}),
					})
					.then((res) => res.json())
					.then((response) => {
						if (response.errors) {
							throw new Error(response.errors);
						}
						let { action, href, textAddedCart, target, messageAddedCart } =
							submitButton.dataset;
						if (submitButton) {
							submitButton.style.cursor = "pointer";
							submitButton.style.pointerEvents = "auto";
							submitButton.classList.remove(
								"ecom-ajax-loading",
								"ecom-loading"
							);
							submitButton.querySelector(
								".ecom-add-to-cart-text"
							).innerHTML = textAddedCart;
						}
						if (_this.onAjaxCartSuccess) {
							_this.onAjaxCartSuccess(response, event.target);
						}
		
						if (list && !_this.configs.ajax_cart.enable) {
							return setTimeout(function () {
								return (window.location.href = _this.routes.cart_url);
							}, 500);
						}
						switch (action) {
							case "cart":
								return setTimeout(function () {
									return (window.location.href =
										_this.routes.cart_url);
								}, 500);
							case "reload":
								return setTimeout(function () {
									return window.location.reload();
								}, 500);
							case "checkout":
								return setTimeout(function () {
									return (window.location.href =
										_this.routes.root_url + "checkout");
								}, 500);
							case "message":
								_this.showToast(messageAddedCart);
								break;
							case "link":
								if (href) {
									return setTimeout(function () {
										if (target === "_blank") {
											return window.open(href);
										} else {
											return (window.location.href = href);
										}
									}, 500);
								}
							default:
								_this.ajaxCartSuccess(response, event.target);
								break;
						}
					})
					.catch((e) => {
						window.alert(e.message);
						console.error(e);
						if (submitButton) {
							submitButton.style.cursor = "pointer";
							submitButton.style.pointerEvents = "auto";
							submitButton.classList.remove(
								"ecom-ajax-loading",
								"ecom-loading"
							);
						}
						_this.ajaxCartError(e, event.target);
					});
			};
			window.EComposer.ajaxCartSuccess = function (data, form) {
				const selectors$n = {
					cartWrapper: ".quick-cart__wrapper",
					innerContainer: ".quick-cart__container",
					overlay: ".quick-cart__overlay",
					closeButton: ".quick-cart__close-icon",
					footer: ".quick-cart__footer",
					items: ".quick-cart__items",
					cartError: ".quick-cart__item-error",
					form: ".quick-cart__form",
					cartCount: ".quick-cart__heading sup",
					subtotal: ".quick-cart__footer-subtotal span",
					quantityInput: ".quick-cart .quantity-input__input",
					quantityItem: "[data-input-item]",
					discounts: ".quick-cart__item-discounts"
				};
				let url = "".concat(theme.routes.cart.base, "?section_id=quick-cart"),
					cartCounts = document.querySelectorAll('[data-js-cart-count]');
				function updateInnerHTML(selector, doc) {
					var updatedItem = n$2(selector, doc);
					var oldItem = n$2(selector);
				  
					if (updatedItem && oldItem) {
					  oldItem.innerHTML = updatedItem.innerHTML;
					}
				}
				function adjustItemPadding() {
					var items = n$2(selectors$n.items, this.container);
					if (!items) return; // Ensure cart items accounts for the height of cart footer
				
					var footer = n$2(selectors$n.footer, this.container);
					items.style.paddingBottom = "".concat(footer.clientHeight, "px");
				}
				let delayOffset = (function (node, items) {
					let offsetStart = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
					var delayOffset = offsetStart;
					items.forEach(function (selector) {
					  var items = t$2(selector, node);
					  items.forEach(function (item) {
						item.style.setProperty("--delay-offset-multiplier", delayOffset);
						delayOffset++;
					  });
					});
				});
				let selectors$15 = {
					animationItem: ".animation--quick-cart-items > *, .animation--quick-cart-footer"
				};
				function n$2(n,t){return void 0===t&&(t=document),t.querySelector(n)}function t$2(n,t){return void 0===t&&(t=document),[].slice.call(t.querySelectorAll(n))}function c$1(n,t){return Array.isArray(n)?n.forEach(t):t(n)}function r$2(n){return function(t,r,e){return c$1(t,function(t){return t[n+"EventListener"](r,e)})}}function e$2(n,t,c){return r$2("add")(n,t,c),function(){return r$2("remove")(n,t,c)}}function o$2(n){return function(t){var r=arguments;return c$1(t,function(t){var c;return (c=t.classList)[n].apply(c,[].slice.call(r,1))})}}function u$1(n){o$2("add").apply(void 0,[n].concat([].slice.call(arguments,1)));}function i$1(n){o$2("remove").apply(void 0,[n].concat([].slice.call(arguments,1)));}function l(n){o$2("toggle").apply(void 0,[n].concat([].slice.call(arguments,1)));}function a$1(n,t){return n.classList.contains(t)}
				fetch(url)
				  .then((response => response.text()))
				  .then((response) => {
					var container = document.createElement("div");
					container.innerHTML = response;
					var responseInnerContainer = n$2(selectors$n.innerContainer, container);
					var cartHasItems = Boolean(n$2(selectors$n.items, cart.parentNode));
					var responseHasItems = Boolean(n$2(selectors$n.items, container)); // Cart has items and needs to update them
					if (responseHasItems && cartHasItems) {

						// Render cart items
						updateInnerHTML("".concat(selectors$n.cartWrapper, " ").concat(selectors$n.items), container);

						adjustItemPadding(); // Render cart count


						updateInnerHTML("".concat(selectors$n.cartWrapper, " ").concat(selectors$n.cartCount), container); // Render subtotal

						updateInnerHTML("".concat(selectors$n.cartWrapper, " ").concat(selectors$n.subtotal), container); // Render promotions

						updateInnerHTML("".concat(selectors$n.cartWrapper, " ").concat(selectors$n.discounts), container); // Handle form scroll state

						var form = n$2(selectors$n.form, cart.parentNode);
						var previousScrollPosition = form.scrollTop || 0;
						form.scrollTop = previousScrollPosition;
						delayOffset(cart.parentNode, [selectors$15.animationItem]);
					}
					else {
						let innerContainer = n$2(selectors$n.innerContainer, cart.parentNode);
						innerContainer.innerHTML = responseInnerContainer.innerHTML;
					}
					fetch('/cart.js')
					.then(res => res.json())
					.then(res => {
						cartCounts.forEach(cartCount => {
							cartCount.innerHTML = res.item_count;
						})
					});
					document.documentElement.classList.add('prefers-reduced-motion');
					cart.classList.add('active')
				})
				.catch((e) => {
					console.error(e);
				});
			};
		}
	}, 2000);
});

11. With the Basel theme

setTimeout(function() {

  if(window.EComposer){
      EComposer.ajaxCartSuccess = function(data,f){
        window.location.hash="ec-added-cart";
        window.location.reload();
          
      }
  }
}, 2000)
document.addEventListener('DOMContentLoaded', function() {
if(window.location.hash.includes('ec-added-cart')){
   
  setTimeout(function(){
    const cart = document.querySelector('.main-header .basel-cart-icon a:not(.clicked)');
    console.log(cart);
    if(cart) {
      cart.click();
      cart.classList.add('clicked');
         
      window.location.hash='';
       
    }
      
  },1000);
 
}
})

12. With the Uminex theme

document.addEventListener('DOMContentLoaded', function() {
    setTimeout(function() {
        if(window.EComposer) {
            window.EComposer.ajaxCartSuccess = function(data, form) {
                console.log('XXX add');
                $('body').trigger('update:miniCart');
                $('.push_side[data-id="#js_cart_popup"]').trigger('click');
            }
        }
    }, 1000);
})

12. With the Focal theme

You can download the Focal theme here

document.addEventListener("DOMContentLoaded",function() {
    setTimeout(function() {
        if(window.EComposer) {
            window.EComposer.ajaxCartSuccess = function(data, form) {
                document.documentElement.dispatchEvent(new CustomEvent('cart:refresh', {
                    bubbles: true
                }));
                document.getElementById('mini-cart').open = true;
                fetch('/cart.json').then(res => res.json()).then(cart => {
                    document.querySelector('cart-count').innerText = cart.item_count
                })
            }
        }
    }, 1000);
})

13. With the Symmetry theme

You can download the theme here

document.addEventListener("DOMContentLoaded", function () {
  setTimeout(function() {
    if(window.EComposer){
        EComposer.ajaxCartSuccess = function(data,f){
        document.documentElement.dispatchEvent(
      new CustomEvent('theme:cartchanged', { bubbles: true, cancelable: false, detail: { openDrawer: true } }));
    }
    }
  }, 2000)
})

The below code is for Symmetry 7.x versions:

document.addEventListener("DOMContentLoaded", function () {
  setTimeout(function() {
    const cart = document.querySelector('cart-drawer');
    const header = document.querySelector('page-header');
    const headerSection = header.dataset.sectionId
    const cartSection = cart.dataset.sectionId;
    if(window.EComposer){
        EComposer.ajaxCartSuccess = function(data,f){
            fetch(`/?sections=${cartSection},${headerSection}`)
            .then((res) => res.text())
            .then((res) => {
                const sections = JSON.parse(res);
                cart.querySelector('cart-form').refreshFromHtml(sections[cartSection]);
                const template = document.createElement('template');
                const selectorForUpdate = '.logo-area__right'
                template.innerHTML = sections[headerSection];
                header.querySelector(selectorForUpdate).innerHTML = template.content.querySelector(selectorForUpdate).innerHTML;;
                document.querySelector('.js-cart-drawer').open();
            })
        }
    }
  }, 1000)
})

14. With the Be Yours theme

document.addEventListener("DOMContentLoaded", function () {
    
  setTimeout(function() {

    if(window.EComposer){
        const sticky = document.querySelector('.ecom-sticky__atc.ecom-sticky-show');
        EComposer.ajaxCartSuccess = function(data,f){
            fetch('/?sections=mini-cart,cart-icon-bubble,mobile-cart-icon-bubble')

            .then((response) => response.json())

            .then((res) => {

                const minicart  = document.querySelector('mini-cart');
                data.sections = res
                
                minicart.renderContents(data);

            })

            .catch((e) => {

                console.error(e);

            })
            .finally(function() {
                if(sticky) {
                    sticky.style.display = 'none';
                }
            })


        }

    }

  }, 2000)

})

15. With the Refresh – Spotlight theme

document.addEventListener("DOMContentLoaded", function () {

  setTimeout(function () {

    if (window.EComposer) {

      window.EComposer.ajaxCartSuccess = function (data, form) {

        const cart = document.querySelector("cart-notification") || document.querySelector("cart-drawer");

        if (cart) {
            fetch('/?sections=cart-notification-product,cart-notification-button,cart-icon-bubble,cart-drawer')
            .then((res) => res.json())
            .then((res) => {
                console.log(res);
                data.sections = res;
                cart.renderContents(data);
                cart.classList.remove('is-empty');
            })
        }

      };
    }

  }, 1000);

});

16. With the Ecomus theme of The4

document.addEventListener("DOMContentLoaded", function () {
  setTimeout(function () {
    if (window.EComposer) {
      window.EComposer.ajaxCartSuccess = function (data, form) {
        document.getElementById('CartDrawer')?.openDialog();
        document.documentElement.dispatchEvent(new CustomEvent('cart:refresh', {
            bubbles: true
        }));
      };
    }
  }, 1500);
});

17. With the Impulse theme

You can download the Impulse theme here

/* Impulse */
document.addEventListener("DOMContentLoaded", function () {
  setTimeout(function () {
    if (window.EComposer) {
      window.EComposer.ajaxCartSuccess = function (data, form) {
        document.dispatchEvent(new CustomEvent("ajaxProduct:added"));
      };
    }
  }, 1000);
});

18. With the Prestige theme

document.addEventListener("DOMContentLoaded", function () {
  setTimeout(function () {
    if (window.EComposer) {
      window.EComposer.ajaxCartSuccess = function (data, form) {
        console.log('%cECOM DEBUG - VAR: data', 'color: #6dec6d', data)
        document.dispatchEvent(new CustomEvent("product:added", {
          bubbles: !0,
          detail: {
            variant: data.variant_id,
            quantity: 1
          }
        }));
      };
    }
  }, 1500);
});

19. With the Minimog theme

document.addEventListener("DOMContentLoaded", function () {
  setTimeout(function () {
    if (window.EComposer) {
      EComposer.ajaxCartSuccess = function (data, f) {
        const cart = document.querySelector('m-cart-drawer');
        if(cart) {
            cart.renderContents(data)
            cart.open();
            cart.getCart().then((t=>{
                    cart.classList.toggle("m-cart--empty", 0 === t.item_count),
                    cart.updateCartCount(t.item_count)
                }
            ))
        }
      }
    }
  }, 1000)
});

20. With the Norman theme

You can buy this theme here

document.addEventListener("DOMContentLoaded", function () {

  setTimeout(function () {

    if (window.EComposer) {

      window.EComposer.ajaxCartSuccess = function (data, form) {
        window.theme.miniCart.updateElements()
        window.theme.miniCart.generateCart();
      };

    }

  }, 1000);

});

21. With the Reformation theme

document.addEventListener("DOMContentLoaded", function () {

  setTimeout(function () {

    if (window.EComposer) {

      window.EComposer.ajaxCartSuccess = function (data, form) {
        function getSectionsToRender() {
            return [{
                id: 'Cart',
                section: 'main-cart',
                selector: '.thb-cart-form'
            },
            {
                id: 'Cart-Drawer',
                section: 'cart-drawer',
                selector: '.cart-drawer'
            },
            {
                id: 'cart-drawer-toggle',
                section: 'cart-bubble',
                selector: '.thb-item-count'
            }];
        }
        function getSectionInnerHTML(html, selector = '.shopify-section') {
            return new DOMParser()
                .parseFromString(html, 'text/html')
                .querySelector(selector).innerHTML;
        }
        function renderContents(parsedState) {
          getSectionsToRender().forEach((section => {
            if (!document.getElementById(section.id)) {
              return;
            }
            const elementToReplace = document.getElementById(section.id).querySelector(section.selector) || document.getElementById(section.id);
            elementToReplace.innerHTML = getSectionInnerHTML(parsedState.sections[section.section], section.selector);
            if (typeof CartDrawer !== 'undefined') {
              new CartDrawer();
            }
            if (typeof Cart !== 'undefined') {
              new Cart().renderContents(parsedState);
            }
          }));
    
    
          if (document.getElementById('Cart-Drawer')) {
            document.getElementById('Cart-Drawer').classList.add('active');
            document.body.classList.add('open-cart');
            document.body.classList.add('open-cc');
            if (document.getElementById('Cart-Drawer').querySelector('.product-recommendations--full')) {
              document.getElementById('Cart-Drawer').querySelector('.product-recommendations--full').classList.add('active');
            }
            dispatchCustomEvent('cart-drawer:open');
          }
        }
        fetch('/?sections=cart-bubble,cart-drawer,main-cart')
        .then((res) => res.json())
        .then((res) => {
            console.log(res);
            data.sections = res;
            renderContents(data);
        })

      };
    }

  }, 1000);

});

22. With the Ella theme

document.addEventListener("DOMContentLoaded", function () {
  setTimeout(function () {
    if (window.EComposer) {
      window.EComposer.ajaxCartSuccess = function (data, form) {
        window.halo.initSidebarCart()
        fetch('/cart.json')
        .then(res => res.json())
        .then((res) => {
            window.halo.updateSidebarCart(res);
            window.halo.updateCart(res);
            document.querySelector('body').classList.add('cart-sidebar-show')
        })
       
      };
    }
  }, 1500);
});

23. With the Flow theme

document.addEventListener("DOMContentLoaded", function () {

    setTimeout(function () {

      if (window.EComposer) {

        window.EComposer.ajaxCartSuccess = async function (data, form) {

            const i = await window.fetch(/cart?view=compare);

              if (!i.ok) return !1;

              const o = await i.json();

              wetheme.toggleRightDrawer("cart", !0, { cart: o })

        };

      }

    }, 1000);

  });

24. With the Yuva theme

document.addEventListener("DOMContentLoaded", function () {

    setTimeout(function () {

      if (window.EComposer) {

        window.EComposer.ajaxCartSuccess = async function (data, form) {

            $("body").find("[data-side-drawer]").attr("class", "yv_side_drawer_wrapper");

            $("body").find("[data-drawer-title]").html(cartTitleLabel);

            $("body").find("[data-side-drawer]").attr("id", "mini__cart");

            $("body").find("[data-side-drawer]").addClass("mini_cart");

            $("body").removeClass("quickview-open");

            $("body").addClass("side_Drawer_open");

            jQuery.getJSON(cartUrl, function (a, e) {

              buildCart(a, !0);

            });

            

        };

      }

    }, 1000);

  });

25. With other themes (which support the Cart Drawer function)

This is the code for those themes:

document.addEventListener("DOMContentLoaded", function () {
  setTimeout(function() {
    if(window.EComposer){
        EComposer.ajaxCartSuccess = function(data,f){
          window.location.hash="ec-added-cart";
          window.location.reload();
        }
    }
  }, 2000)
 
if(window.location.hash.includes('ec-added-cart')){
  setTimeout(function(){
    const cart = document.querySelector('button#CartButton:not(.clicked)');
    if(cart) {
      cart.click();
      cart.classList.add('clicked');
      window.location.hash='';
    }
  },500);
}
})

Note: The red one (.button#CartButton) from the code above needs to be changed depending on each theme.

You can inspect the website (or press F12) to find a suitable selector. If you can’t do it by yourself, don’t hesitate to contact us via live chat.

26. With the Upcart app

document.addEventListener("DOMContentLoaded", function () {
  setTimeout(function () {
    if (window.EComposer) {
      window.EComposer.ajaxCartSuccess = function (data, form) {
       return true;
      };
    }
  }, 1500);
});

Leave a Comment

Enjoy a free 3-day trial. Then get your first month for $1. Try Now.