dynamic free shipping bar - Debut theme

Highlighted
Shopify Partner
32 2 5

Hi,
I coded a dynamic freeshipping bar on Debut theme, it works great, except one thing; the user must reload the page to update the shipping bar info.

How can i do in order to update automatically this shipping bar when a user add an item to its cart ?

Thanks in advance

{% assign announc-bfr-prc = section.settings.announc-bfr %}
{% assign free-ship = section.settings.free-shipping %}
{% assign announc-aftr-prc = section.settings.announc-aftr %}
{% assign announc-freshp = section.settings.announc-freshp %}
{% assign ship-prc-bfr = free-ship | times: 100.0 | minus: cart.total_price %}
<div class="gd-free-shipping-bar">
{% if ship-prc-bfr > 0 %}
<p>{{ announc-bfr-prc }} <strong>{{ship-prc-bfr | money }}</strong> {{ announc-aftr-prc }} </p>
{% else %}
<span>{{ announc-freshp }}</span>
{% endif %}
</div>
<style>
.gd-free-shipping-bar p {
color:{{settings.txt-bfr-freeship}};
background-color:{{settings.bk-bfr-freeship}};
text-align:center;
width:100%;
display:block;
padding:15px 10px;
margin:0 auto 5px;
}
.gd-free-shipping-bar span {
color:{{settings.txt-aftr-freeship}};
background-color:{{settings.bk-aftr-freeship}};
text-align:center;
width:100%;
display:block;
padding:15px 10px;
margin:0 auto 5px; }
</style>
Shopify lover
0 Likes
Shopify Partner
1935 321 406

Hi @CodingLover 

If you want to change you shipping info base on cart product in real time then you have to deal with Js code.

Find Ajax add to cart function in your Asset->theme.js (in most case) and change your shipping info base on you product real time, you can change info in ajax success function because you can get cart json in response after product added.  

Want to modify or custom changes on store hire me.
If helpful then please Like and Accept Solution.
Email: jasoliyabrijesh123@gmail.com
Skype: jasoliya.brijesh
Want to get Free review and advice for sale on store ?? just text me here
0 Likes

@Jasoliya is right.

I guess you followed this guide (for creating Ajax Add to cart) on Debut theme. 

By improvising your code and the guide above , i was able to create what you were trying to achieve on Alternate Product Template (It would only work on this product page) https://nichegeek.myshopify.com/products/champion-ii-headgear

 

Here is the code.

 

{% assign announc-bfr-prc = 'ADD ITEMS WORTH ' %}

{% assign announc-after-prc = 'FOR FREE SHIPPING ' %}

{% assign free-ship = '120' | times: 100.0 %}

{% assign announc-freshp = 'YAY! YOU HAVE FREE SHIPPING' %}

{% assign ship-prc-bfr = free-ship | minus: cart.total_price %}

<div class="gd-free-shipping-bar" data-threshold="{{free-ship}}" data-format="{{shop.money_format}}">
  {% if ship-prc-bfr > 0 %}
  <p>{{ announc-bfr-prc }} <strong>{{ ship-prc-bfr | money_without_trailing_zeros  }}</strong> {{announc-after-prc}}  </p>
  {% else %}
  <span>{{ announc-freshp }}</span>
  {% endif %}
</div>

<style>
  .gd-free-shipping-bar p {
    color: white;
    background-color:red;
    text-align:center;
    width:100%;
    display:block;
    padding:15px 10px;
    margin:0 auto 5px;
  }
  .gd-free-shipping-bar span {
    color:green;
    background-color: yellow;
    text-align:center;
    width:100%;
    display:block;
    padding:15px 10px;
    margin:0 auto 5px; }
</style>
Shopify.AjaxifyCart = (function($) {
  
  // Some configuration options.
  // I have separated what you will never need to change from what
  // you might change.
  var targetPrice
  var _config = {
    
    // What you might want to change
    addToCartBtnLabel:             'Add to cart',
    addedToCartBtnLabel:           'Thank you!',
    addingToCartBtnLabel:          'Adding...',
    soldOutBtnLabel:               'Sold Out',
    howLongTillBtnReturnsToNormal: 1000, // in milliseconds.
    cartCountSelector:             '.cart-count,#CartCount span, #cart-count a:first, #gocart p a, #cart .checkout em, .item-count',
    cartTotalSelector:             '#cart-price',
    // 'aboveForm' for top of add to cart form, 
    // 'belowForm' for below the add to cart form, and 
    // 'nextButton' for next to add to cart button.
    feedbackPosition:              'nextButton',
    
    // What you will never need to change
    addToCartBtnSelector:          '[type="submit"]',
    addToCartFormSelector:         'form[action="/cart/add"]',
    shopifyAjaxAddURL:             '/cart/add.js',
    shopifyAjaxCartURL:            '/cart.js',
    freeShipping:		   $('.gd-free-shipping-bar').data('threshold')
  };
  
  // We need some feedback when adding an item to the cart.
  // Here it is.  
  var _showFeedback = function(success, html, $addToCartForm) {
    $('.ajaxified-cart-feedback').remove();
 
    var feedback = '<p class="ajaxified-cart-feedback ' + success + '">' + html + '</p>';
    switch (_config.feedbackPosition) {
      case 'aboveForm':
        $addToCartForm.before(feedback);
        break;
      case 'belowForm':
        $addToCartForm.after(feedback);
        break;
      case 'nextButton':
      default:
        $addToCartForm.find(_config.addToCartBtnSelector).after(feedback);
        break;   
    }
    // If you use animate.css
    // $('.ajaxified-cart-feedback').addClass('animated bounceInDown');
    $('.ajaxified-cart-feedback').slideDown();
  };
  var _setText = function($button, label) {
    if ($button.children().length) {
      $button.children().each(function() {
        if ($.trim($(this).text()) !== '') {
          $(this).text(label);
        }
      });
    }
    else {
      $button.val(label).text(label);
    }
  };
  var _init = function() {   
    $(document).ready(function() { 
      $(_config.addToCartFormSelector).submit(function(e) {
        e.preventDefault();
        var $addToCartForm = $(this);
        var $addToCartBtn = $addToCartForm.find(_config.addToCartBtnSelector);
        _setText($addToCartBtn, _config.addingToCartBtnLabel);
        $addToCartBtn.addClass('disabled').prop('disabled', true);
        // Add to cart.
        $.ajax({
          url: _config.shopifyAjaxAddURL,
          dataType: 'json',
          type: 'post',
          data: $addToCartForm.serialize(),
          success: function(itemData) {
            // Re-enable add to cart button.
            $addToCartBtn.addClass('inverted');
            _setText($addToCartBtn, _config.addedToCartBtnLabel);
            _showFeedback('success','<i class="fa fa-check"></i> Added to cart! <a href="/cart">View cart</a> or <a href="/collections/all">continue shopping</a>.',$addToCartForm);
            window.setTimeout(function(){
              $addToCartBtn.prop('disabled', false).removeClass('disabled').removeClass('inverted');
              _setText($addToCartBtn,_config.addToCartBtnLabel);
            }, _config.howLongTillBtnReturnsToNormal);
            // Update cart count and show cart link.
            $.getJSON(_config.shopifyAjaxCartURL, function(cart) {
              if (_config.cartCountSelector && $(_config.cartCountSelector).size()) {
                var value = $(_config.cartCountSelector).html() || '0';
                $(_config.cartCountSelector).html(value.replace(/[0-9]+/,cart.item_count)).removeClass('hidden-count');
              }
              
              //Debut theme Specific
              if($('#CartCount').length == 0){
                $('a.site-header__cart').append('<div id="CartCount" class="site-header__cart-count"><span>'+cart.item_count+'</span></div>')
              }
              
              targetPrice = ($(_config.freeShipping).selector - cart.total_price)
              
              if(targetPrice > 0){
                $('.gd-free-shipping-bar strong').html(Shopify.formatMoney(targetPrice,"${{amount}}"))

              }else{
		 location.reload();
              }

              
            });        
          }, 
          error: function(XMLHttpRequest) {
            var response = eval('(' + XMLHttpRequest.responseText + ')');
            response = response.description;
            if (response.slice(0,4) === 'All ') {
              _showFeedback('error', response.replace('All 1 ', 'All '), $addToCartForm);
              $addToCartBtn.prop('disabled', false);
              _setText($addToCartBtn, _config.soldOutBtnLabel);
              $addToCartBtn.prop('disabled',true);
            }
            else {
              _showFeedback('error', '<i class="fa fa-warning"></i> ' + response, $addToCartForm);
              $addToCartBtn.prop('disabled', false).removeClass('disabled');
              _setText($addToCartBtn, _config.addToCartBtnLabel);
            }
          }
        });   
        return false;    
      });
    });
  };
  return {
    init: function(params) {
        // Configuration
        params = params || {};
        // Merging with defaults.
        $.extend(_config, params);
        // Action
        $(function() {
          _init();
        });
    },    
    getConfig: function() {
      return _config;
    }
  }  
})(jQuery);

Shopify.AjaxifyCart.init();

Hope you can write a better version out of this :)

   

Available for hiring. Inbox me lixonic[at]gmail[dot]com
1 Like
Shopify Partner
32 2 5

Hi @Lixon_Louis 

Thanks or your time and for code, but obviously this one reload the entire page when a user add an item to its cart, and this is not good for user experience.

Best regards,

Shopify lover
0 Likes

@CodingLover  Well, I hope you know how to remove location.reload() and write code to display the message without disturbing the UX. Just curious to know , does the given product page link reloads after you hit add to cart? I presumed that it will only reload if the free shipping target is met! 

Available for hiring. Inbox me lixonic[at]gmail[dot]com
1 Like
New Member
1 0 0

This is awesome!

 

I'm looking to do something like this but on the drawer cart. How would you recommend I go about doing this?

 

Screen Shot 2019-08-16 at 6.15.34 PM.png

0 Likes
Shopify Partner
32 2 5

Hi Lixon,

i resolved the issue i changed this line from 

<div class="gd-free-shipping-bar" data-threshold="{{free-ship}}" data-format="{{shop.money_format}}">

to

<div class="gd-free-shipping-bar" data-threshold="{{ship-prc-bfr}}" data-format="{{shop.money_format}}">

Thank again

 

Shopify lover
1 Like
Shopify Partner
32 2 5

Hi @JamesBake ,
Create a snippet and name it for instance freeshipping-bar.liquid then past the codes above in it and include it in your cart template where you want it to be appeared

{% include 'freeshipping-bar' %}

 

Shopify lover
0 Likes

@JamesBake The solution i proposed is theme dependent . Are you using Debut?

Available for hiring. Inbox me lixonic[at]gmail[dot]com
0 Likes