[Special Summer Sale] 40% OFF All Magento 2 Themes

Cart

Update cart drawer without reloading the page in shopify

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #9617
    sunny
    Participant

    I want to update cart drawer when I click on add to cart button currently got value but only when I reload the page is there any way to refresh value without reloading page. I am using debut theme.

    This is my code:

    <form action="{{ routes.cart_url }}" method="post" novalidate class="cart">
    
            
            <div  class="cart_popup_wrapper" data-cart-line-items>
              {%- for item in cart.items -%}
                <div  class="cart__row" data-cart-item data-cart-item-key="{{ item.key }}" data-cart-item-url="{{ item.url }}" data-cart-item-title="{{ item.title }}" data-cart-item-index="{{ forloop.index }}" data-cart-item-quantity="{{ item.quantity }}">
                  <div  class="cart_popup" data-cart-table-cell>
                    <div class="cart__product-information cart_popup_data">
                      <div class="cart_popup_image-wrapper">
                        <img class="cart__image{% if item.image == null %} hide{% endif %}" src="{{ item | img_url: 'x190' }}" alt="{{ item.image.alt | escape }}" data-cart-item-image>
                      </div>
                      <div class="cart_popup_data">
                        <div class="list-view-item__title">
                          <a href="{{ item.url }}" class="cart__product-title" data-cart-item-title>
                            {{ item.product.title }}
                          </a>
                        </div>
    
                        {%- assign variant_options = 'template ' | split: ' ' -%}
                        {%- if item.product.has_only_default_variant != true -%}
                          {%- assign variant_options = item.options_with_values -%}
                        {%- endif -%}
                        {%- assign property_size = item.properties | size -%}
    
                        <ul class="product-details{% if item.product.has_only_default_variant and property_size == 0 %} hide{% endif %}" data-cart-item-details aria-label="{{ 'cart.label.product_details' | t }}">
                          {%- for option in variant_options -%}
                            <li class="product-details__item product-details__item--variant-option{% if item.product.has_only_default_variant %} hide{% endif %}" data-cart-item-option>{{ option.name }}: {{ option.value }}</li>
                          {%- endfor -%}
                    
                          {%- assign properties = 'template ' | split: ' ' -%}
                          {%- if property_size > 0 -%}
                            {%- assign properties = item.properties -%}
                          {%- endif -%}
    
                          {%- for p in properties -%}
                            {%- unless p.last == blank -%}
                              <li class="product-details__item product-details__item--property{%if property_size == 0%} hide{% endif %}" data-cart-item-property>
                                <span class="product-details__item-label" data-cart-item-property-name>{{ p.first }}: </span>
    
                                {%- comment -%}
                                  Check if there was an uploaded file associated
                                {%- endcomment -%}
                                <span data-cart-item-property-value>
                                  {%- if p.last contains '/uploads/' -%}
                                    <a href="{{ p.last }}">{{ p.last | split: '/' | last }}</a>
                                  {%- else -%}
                                    {{ p.last }}
                                  {%- endif -%}
                                </span>
                              </li>
                            {%- endunless -%}
                          {%- endfor -%}
                        </ul>
                        <div  class="cart_popup__price">
    
                    {%- assign hasDiscount = false -%}
                    {%- if item.original_price != item.final_price -%}
                      {%- assign hasDiscount = true -%}
                    {%- endif -%}
    
                    <div data-cart-item-price>
                      <dl data-cart-item-price-list>
                        {%- comment -%}
                          Markup template for discount item
                        {%- endcomment -%}
                        <div {% unless hasDiscount %}class="hide" {% endunless %}data-cart-item-discounted-price-group>
                          <dt>
                            <span class="visually-hidden">{{ 'products.product.regular_price' | t }}</span>
                          </dt>
                          <dd>
                            <s data-cart-item-original-price>{{ item.original_price | money }}</s>
                          </dd>
                          <dt>
                            <span class="visually-hidden">{{ 'products.product.sale_price' | t }}</span>
                          </dt>
                          <dd>
                            <span class="order-discount" data-cart-item-final-price>{{ item.final_price | money }}</span>
                          </dd>
                        </div>
    
                        {%- comment -%}
                          Markup template for regular price item
                        {%- endcomment -%}
                        <div {% if hasDiscount %}class="hide" {% endif %}data-cart-item-regular-price-group>
                          <dt>
                            <span class="visually-hidden">{{ 'products.product.regular_price' | t }}</span>
                          </dt>
                          <dd data-cart-item-regular-price>
                            {{ item.original_price | money }}
                          </dd>
                        </div>
    
                        {%- comment -%}
                          Markup template for unit price
                        {%- endcomment -%}
                        <div {% unless item.unit_price_measurement %}class="hide" {% endunless %}data-unit-price-group>
                          <dt>
                            <span class="visually-hidden visually-hidden--inline">{{ 'products.product.unit_price_label' | t }}</span>
                          </dt>
                          <dd>
                            <span class="price-unit-price">
                              {%- capture unit_price_separator -%}
                                <span aria-hidden="true">/</span><span class="visually-hidden">{{ 'general.accessibility.unit_price_separator' | t }}&nbsp;</span>
                              {%- endcapture -%}
                              {%- capture unit_price_base_unit -%}
                                {%- if item.unit_price_measurement.reference_value != 1 -%}
                                  {{- item.unit_price_measurement.reference_value -}}
                                {%- endif -%}
                                {{ item.unit_price_measurement.reference_unit }}
                              {%- endcapture -%}
    
                              <span data-unit-price>{{ item.unit_price | money }}</span>{{- unit_price_separator -}}<span data-unit-price-base-unit>{{- unit_price_base_unit -}}</span>
                            </span>
                          </dd>
                        </div>
                      </dl>
                    </div>
    
                    {%- assign itemDiscounts = 'template ' | split: ' ' -%}
                    {%- if item.line_level_discount_allocations != blank -%}
                      {%- assign itemDiscounts = item.line_level_discount_allocations -%}
                    {%- endif -%}
    
                    <ul class="order-discount order-discount--list order-discount--title order-discount--cart{% if item.line_level_discount_allocations == blank %} hide{% endif %}" aria-label="{{ 'customer.order.discount' | t }}" data-cart-item-discount-list>
                      {%- for discount_allocation in itemDiscounts -%}
                        <li class="order-discount__item" data-cart-item-discount>
                          {% include 'icon-saletag' %}
                          <span data-cart-item-discount-title>
                            {{- discount_allocation.discount_application.title -}}
                          </span> (-<span data-cart-item-discount-amount>{{ discount_allocation.amount | money }}</span>)
                        </li>
                      {%- endfor -%}
                    </ul>
    
                    <div class="cart__qty medium-up--hide">
                      <label for="updates_{{ item.key }}" class="cart__qty-label" aria-label="{{ 'cart.label.quantity' | t }}" data-quantity-label-mobile>
                        {{ 'cart.label.qty' | t }}
                      </label>
                      <input id="updates_{{ item.key }}" class="cart__qty-input" type="number"
                        value="{{ item.quantity }}" min="0" pattern="[0-9]*"
                        data-quantity-input data-quantity-item="{{ forloop.index }}" data-quantity-input-mobile>
                    </div>
                    <div class="cart__qty-error-message-wrapper cart__qty-error-message-wrapper--mobile hide" role="alert" data-cart-quantity-error-message-wrapper>
                      <span class="visually-hidden">{{ 'general.accessibility.error' | t }} </span>
                      {% include 'icon-error' %}
                      <span class="cart__qty-error-message" data-cart-quantity-error-message></span>
                    </div>
                  </div>   
                        
                        <div class="qty_remove">
                            <div class="cart__quantity-td text-right small--hide">
                        <div class="cart_drawer__qty">
                          <label for="updates_large_{{ item.key }}" class="cart__qty-label" data-quantity-label-desktop>{{ 'cart.label.quantity' | t }}</label>
                           <span class="minus_cart_item">-</span>
                          <input id="updates_large_{{ item.key }}" class="cart__qty-input" type="number"
                            name="updates[]" value="{{ item.quantity }}" min="0" pattern="[0-9]*"
                            data-quantity-input data-quantity-item="{{ forloop.index }}" data-quantity-input-desktop>
                           <span class="plus_cart_item">+</span>
                          
                        </div>
                        <div class="cart__qty-error-message-wrapper cart__qty-error-message-wrapper--desktop hide" role="alert" data-cart-quantity-error-message-wrapper>
                          <span class="visually-hidden">{{ 'general.accessibility.error' | t }} </span>
                          {% include 'icon-error' %}
                          <span class="cart__qty-error-message" data-cart-quantity-error-message></span>
                        </div>
    </div>                                    
                            <p class="cart__remove">
                          <a href="/cart/change?line={{ forloop.index }}&amp;quantity=0" class="text-link text-link--accent" aria-label="{{ 'cart.label.remove' | t: product: item.title }}" data-cart-remove>{{ 'cart.general.remove' | t }}</a>
                        </p>
                        </div>
                        
                      </div>
                    </div>
                  </div >   
                </div>
              {%- endfor -%}
            </div>
    
    #9618

    Reload Cart Page When Product Quantity is Changed

    https://community.shopify.com/c/Technical-Q-A/Reload-Cart-Page-When-Product-Quantity-is-Changed/m-p/856240#M32729

    <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>
    
    #9619
    cyberspider789
    Participant

    This is not an answer but an attempt being shared with community and fellow coder for help because I have worked a lot on this but unresolvable !

    I am facing the same issue. Add 1st product to cart, cart appears but nothing inside cart. Add second product to cart–vola ! both products appears !! However, if I use shopify’s regular ‘Add to cart’ button, even first product appears on first attempt of adding it and cart appears ok….

    Code of added a new asset JS script called atc-now.js is as below. and it is added in theme.liquid appropriately with defer attribute.

    Code preamble: I am capturing a .variant-button’s click event for add-to-cart purpose in atc-now.js so that when .variant-button is clicked, item is added to cart drawer and drawer should appear with the product in it.

    document.addEventListener('DOMContentLoaded', function()
    {
     var variantBut = document.querySelector('.variant-button');  
        
     variantBut.addEventListener('click', function() 
     {
            var cart = document.querySelector(".drawer");
            let addToCartForms = document.querySelectorAll('form[action$="/cart/add"]');
          addToCartForms.forEach((form) => 
          {
            form.addEventListener("submit", (e) => 
            {
              e.preventDefault();
              let formData = new FormData(e.target);
    
              const config = {};
              if (cart) 
              {
                formData.append("sections", cart.getSectionsToRender().map((section) => section.id) );
                formData.append("sections_url", window.location.pathname);
                cart.setActiveElement(document.activeElement); 
              }
    
              config.body = formData;
    
              fetch(window.Shopify.routes.root + "cart/add.js", {method: "POST", body: formData,})
                .then((response) => {return response.json();})
                .then((response) => { console.log(response); cart.renderContents(response);})
                .catch((error) => {console.error("Error:", error); });
            });
          });
        });
        
        });
    
Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.