Guide

Ready snippets

Open the Ajax-cart when a user adds a product to the cart

Usually the Ajax-cart isn’t visible and opens when a user clicks the cart icon in the header. The click on the icon triggers a special CSS class to be added that makes the Ajax-cart show up. The simplified code looks like this:

assets/script.js
// Add a special CSS class when the cart-icon is clicked 
document.querySelector("#cart-icon").addEventListener("click", function(){
  document.body.classList.toggle("js-show-ajax-cart");
});
assets/style.css
// The Ajax-cart is hidden by default
.my-ajax-cart {
  display: none;
}

// The Ajax-cart is visible if a special class is added
body.js-show-ajax-cart .my-ajax-cart {
  display: block;
}

Our goal is to add the same CSS class to the body tag when a new product has been just added to the cart:

assets/script.js
// Listen for the "liquid-ajax-cart:request-end" event which is fired
// after a Shopify Cart API Ajax request is performed
document.addEventListener('liquid-ajax-cart:request-end', event => {
  const {requestState} = event.detail;

  // If the "add to cart" request is successful
  if (requestState.requestType === 'add' && requestState.responseData?.ok) {

    // Add the CSS class to the "body" tag
    document.body.classList.add('js-show-ajax-cart');
  }
});