Cart - Add a shipping rates calculator to your cart

TyW
Community Manager
Community Manager
418 40 1141

You can add a shipping rates calculator to your cart page that lets customers estimate their shipping costs before they proceed to the checkout page.

 

calc01.jpg

 

The steps for this tutorial differ depending on whether you are using a sectioned or a non-sectioned theme. A sectioned theme is a newer theme that lets you drag and drop to arrange the layout of your store's pages.

To figure out whether your theme supports sections, go to the theme's Edit code page. If there are files in the Sections directory, you are using a sectioned theme. Non-sectioned themes were released before October 2016, and do not have files in the Sections directory.

If you are using a sectioned theme, then click the Sectioned themes link and follow the instructions. If you are using an older, non-sectioned theme, then click the Non-sectioned themes link and follow the instructions.

TyW | Online Community Manager @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit the Shopify Help Center or the Shopify Blog

Replies 133 (133)
TyW
Community Manager
Community Manager
418 40 1141

 

Sectioned themes 

Shipping calculator information and features

The shipping rates calculator displays your shipping rates on the cart page of your store. If a customer is logged in, then the calculator uses the customer's default shipping address to estimate shipping rates. The shipping rates calculator works with carrier-calculated rates, manual rates, or a combination of the two.

Keep the following in mind when setting up your shipping calculator:

  • In some situations, the rates are approximations because only the country, province/state, and postal/zip code are provided for the calculation, rather than the full address. The exact rates are given at checkout.
  • The displayed text can be translated.
  • Rates are formatted in your shop's currency and include the currency descriptor, such as CAD or USD.
  • The HTML for the calculator is easy to edit if you know the basics.
  • The calculator uses an Underscore.js template and relies on a JSON API. It uses Ajax to fetch rates from Shopify.
  • There is no equivalent API to calculate applicable taxes on the cart page. Applicable taxes are added at checkout.
  • Shipping calculators currently do not function in Shopify Plus stores that sell in multiple currencies.

 

Note: The shipping calculator only works on the cart page at www.your-shop-url.com/cart. It will not work in a cart drawer or a cart popup. If you are not currently using a cart page, then you can change your cart settings by visiting the theme editor.

Editing your theme code to add the shipping calculator

  1. From your Shopify admin, go to Online Store > Themes.
  2. Find the theme you want to edit, and then click Actions > Edit code.
  3. In the Assets directory, click vendor.js. If your theme doesn't have a vendor.js file, then click theme.js instead.
  4. To the very bottom of vendor.js, paste this code hosted on GitHub. If you are editing theme.js instead, then paste the same code snippet at the very top of the file.
  5. Click Save.
  6. In the Assets directory, click theme.js. To the very bottom of the file, paste the following code:

    Shopify.Cart.ShippingCalculator.show( {
      submitButton: theme.strings.shippingCalcSubmitButton,
      submitButtonDisabled: theme.strings.shippingCalcSubmitButtonDisabled,
      customerIsLoggedIn: theme.strings.shippingCalcCustomerIsLoggedIn,
      moneyFormat: theme.strings.shippingCalcMoneyFormat
    } );
  7. Click Save.
  8. In the Snippets directory, click Add a new snippet.
  9. Name your new snippet shipping-calculator, and click Create snippet:

    calc02.jpg

    Your new snippet will open in the code editor.
  10. Into your new shipping-calculator.liquid snippet, paste this code hosted on GitHub.
  11. Click Save.
  12. In the Sections directory, click cart-template.liquid. If your theme doesn't have a cart-template.liquid file, then, in the Templates directory, click cart.liquid.
  13. Find the closing </form> tag. On a new line right above the closing </form> tag, paste the following code:

    {% render 'shipping-calculator' %}
  14. At the very bottom of the file, paste the following code:

    <script>
      theme.strings = {
          shippingCalcSubmitButton: {{ settings.shipping_calculator_submit_button_label | default: 'Calculate shipping' | json }},
          shippingCalcSubmitButtonDisabled: {{ settings.shipping_calculator_submit_button_label_disabled | default: 'Calculating...' | json }},
          {% if customer %}shippingCalcCustomerIsLoggedIn: true,{% endif %}
          shippingCalcMoneyFormat: {{ shop.money_with_currency_format | json }}
      }
    </script>
    
    <script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.10/handlebars.min.js"></script>
    <script src="/services/javascripts/countries.js"></script>
    <script src="{{ 'shopify_common.js' | shopify_asset_url }}" defer="defer"></script>
  15. Click Save.
  16. In the Config directory, click settings_schema.json. The file will open in the code editor.
  17. Near the very bottom of the file, paste the following code before the last square bracket ] and after the last curly bracket } - make sure to include that first comma , since you're modifying a JSON data structure:

    ,
      {
        "name": "Shipping Rates Calculator",
        "settings": [
          {
            "type": "select",
            "id": "shipping_calculator",
            "label": "Show the shipping calculator?",
            "options": [
              {
                "value": "Disabled",
                "label": "No"
              },
              {
                "value": "Enabled",
                "label": "Yes"
              }
            ],
            "default": "Enabled"
          },
          {
            "type": "text",
            "id": "shipping_calculator_heading",
            "label": "Heading text",
            "default": "Get shipping estimates"
          },
          {
            "type": "text",
            "id": "shipping_calculator_default_country",
            "label": "Default country selection",
            "default": "United States"
          },
          {
            "type": "paragraph",
            "content": "If your customer is logged-in, the country in his default shipping address will be selected. If you are not sure about the  spelling to use here, refer to the first checkout page."
          },
          {
            "type": "text",
            "id": "shipping_calculator_submit_button_label",
            "label": "Submit button label",
            "default": "Calculate shipping"
          },
          {
            "type": "text",
            "id": "shipping_calculator_submit_button_label_disabled",
            "label": "Submit button label when calculating",
            "default": "Calculating..."
          },
          {
            "type": "paragraph",
            "content": "Do not forget to include the snippet shipping-calculator in your cart.liquid template where you want the shipping  calculator to appear. You can get the snippet here: [shipping-calculator.liquid](https:\/\/github.com\/carolineschnapp\/shipping-calculator\/blob\/master\/shipping-calculator.liquid) ."
          }
        ]
      }

Configuring your shipping rates calculator

You can now edit the settings for your shipping rates calculator from the theme editor.

  1. Go to the theme editor.
  2. Under Theme settings, click Shipping Rates Calculator to view and edit the calculator settings.
    You can configure the following settings:
    • Show the shipping calculator? - set this to Yes to display the shipping rates calculator on your cart page, or No to hide it
    • Heading text - enter the text that will be displayed above your shipping rates calculator
    • Default country selection - choose which country will be selected by default
    • Submit button label - enter the text that will be shown on the submit button.

Editing the HTML or CSS of the calculator

Editing the shipping calculator HTML

You can edit the HTML code for your shipping rates calculator to make more advanced customizations.

  1. From your Shopify admin, go to Online Store > Themes.
  2. Find the theme you want to edit, and then click Actions > Edit code.
  3. In the Snippets directory, click shipping-calculator.liquid.
  4. Edit the code as needed. You can add new classes and move the existing HTML elements around in the file to suit your needs.

    Note: Do not edit the HTML ID attributes or the class name "get-rates" on the shipping calculator submit button, as this will interfere with functionality.

  5. Click Save.

Editing the shipping calculator CSS

If you want to change the appearance of your shipping rates calculator, then you can add some CSS to your theme stylesheet.

  1. From your Shopify admin, go to Online Store > Themes.
  2. Find the theme you want to edit, and then click Actions > Edit code.
  3. In the Assets directory, click theme.scss.liquid.
  4. At the very bottom of the file, add either the contents of this CSS file, or your own custom CSS code.
  5. Click Save.

Troubleshooting

Depending on your theme and currency settings, you might see your shipping calculator price estimates displayed on the cart page with un-rendered HTML tags:

calc03.jpg

To remove these unwanted tags, you will need to make a change to your currency settings in the admin.

  1. From your Shopify admin, go to Settings > General.
  2. In the Store currency section, your shop currency is listed. Click Change formatting.
  3. Remove the HTML tags from your currency formats. By default, the settings look like this:

    calc05.jpg
    From both the HTML with currency and the HTML without currency text fields, remove the opening and closing HTML span tags. The result should look like this:

    calc06.jpg
  4. Click Save.

Your shipping calculator price estimates should now display without un-rendered HTML tags:

fixed-70db803ad9ededd688c22ab2bc0e161efde4c99e6996631605e5364d02b9229f.jpg

 

 

 

 

 

 

 

 

 

 

 

 

Demo store

This demo shop has a shipping rates calculator on the cart page.

TyW | Online Community Manager @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit the Shopify Help Center or the Shopify Blog

TyW
Community Manager
Community Manager
418 40 1141

Non-sectioned themes 

Shipping calculator information and features

The shipping rates calculator displays your shipping rates on the cart page of your store. If a customer is logged in, then the calculator uses the customer's default shipping address to estimate shipping rates. The shipping rates calculator works with carrier-calculated rates, manual rates, or a combination of the two.

Keep the following in mind when setting up your shipping calculator:

  • In some situations, the rates are approximations because only the country, province/state, and postal/zip code are provided for the calculation, rather than the full address. The exact rates are given at checkout.
  • The displayed text can be translated.
  • Rates are formatted in your shop's currency and include the currency descriptor, such as CAD or USD.
  • The HTML for the calculator is easy to edit if you know the basics.
  • The calculator uses an Underscore.js template and relies on a JSON API. It uses Ajax to fetch rates from Shopify.
  • There is no equivalent API to calculate applicable taxes on the cart page. Applicable taxes are added at checkout.

Note: The shipping calculator only works on the cart page at www.your-shop-url.com/cart. It will not work in a cart drawer or a cart popup. If you are not currently using a cart page, then you can change your cart settings by visiting the theme editor.

Installing the shipping rates calculator

There are five main steps to install the shipping rates calculator in your theme:

  1. Uploading the file jquery.cart.min.js to your theme assets
  2. Adding settings to the theme editor
  3. Creating a shipping-calculator snippet
  4. Including your snippet in cart.liquid
  5. Configuring your shipping rates calculator

Uploading jquery.cart.min.js to your theme assets

  1. From your Shopify admin, go to Online Store > Themes.
  2. Find the theme you want to edit, and then click Actions > Edit code.
  3. In the Assets directory, click Add a new asset.
  4. Click the Create a blank file tab, and enter jquery.cart.min as the name and select .js as the file extension. Click Add asset.

    calc08-sect.jpg

    Your new blank asset will open in the code editor.
  5. Into your new jquery.cart.min asset, paste this JavaScript code snippet.
  6. Click Save.

Adding settings to the theme editor

  1. In the Config directory, click settings_schema.json. The file will open in the code editor.
  2. Near the very bottom of the file, paste the following code before the last square bracket ] and after the last curly bracket } - make sure to include that first comma , since you're modifying a JSON data structure:

    ,
      {
        "name": "Shipping Rates Calculator",
        "settings": [
          {
            "type": "select",
            "id": "shipping_calculator",
            "label": "Show the shipping calculator?",
            "options": [
              {
                "value": "Disabled",
                "label": "No"
              },
              {
                "value": "Enabled",
                "label": "Yes"
              }
            ],
            "default": "Enabled"
          },
          {
            "type": "text",
            "id": "shipping_calculator_heading",
            "label": "Heading text",
            "default": "Get shipping estimates"
          },
          {
            "type": "text",
            "id": "shipping_calculator_default_country",
            "label": "Default country selection",
            "default": "United States"
          },
          {
            "type": "paragraph",
            "content": "If your customer is logged-in, the country in his default shipping address will be selected. If you are not sure about the  spelling to use here, refer to the first checkout page."
          },
          {
            "type": "text",
            "id": "shipping_calculator_submit_button_label",
            "label": "Submit button label",
            "default": "Calculate shipping"
          },
          {
            "type": "text",
            "id": "shipping_calculator_submit_button_label_disabled",
            "label": "Submit button label when calculating",
            "default": "Calculating..."
          },
          {
            "type": "paragraph",
            "content": "Do not forget to include the snippet shipping-calculator in your cart.liquid template where you want the shipping calculator to appear. You can get the snippet here: [shipping-calculator.liquid](https:\/\/github.com\/carolineschnapp\/shipping-calculator\/blob\/master\/shipping-calculator.liquid) ." } ] }
  3. Click Save.

Creating a shipping-calculator snippet

  1. From your Shopify admin, go to Online Store > Themes.
  2. Find the theme you want to edit, and then click Actions > Edit code.
  3. In the Snippets directory, click Add a new snippet.
  4. Enter shipping-calculator as the name for your new snippet, then click Create snippet:

    calc02.jpg
  5. Your new blank snippet will open in the code editor.
  6. Into your new shipping-calculator snippet, paste this Liquid code snippet.
  7. Click Save.

Including the snippet in cart.liquid

Include your snippet in your cart.liquid file in the place where you want to show your shipping rates calculator. In this example, the calculator is right below the cart form on the cart page.

  1. From your Shopify admin, go to Online Store > Themes.
  2. Find the theme you want to edit, and then click Actions > Edit code.
  3. In the Templates directory, click cart.liquid.
  4. Find the closing </form> tag. On a new line below the tag, paste the following code:

    {% render 'shipping-calculator' %}
  5. Click Save.

Configuring your shipping rates calculator

You can now edit the settings for your shipping rates calculator from the theme editor.

  1. Go to the theme editor.
  2. Under Theme settings, click Shipping Rates Calculator to view and edit the calculator settings.
  3. You can configure the following settings:

    • Show the shipping calculator? - set this to Yes to display the shipping rates calculator on your cart page, or No to hide it
    • Heading text - enter the text that will be displayed above your shipping rates calculator
    • Default country selection - choose which country will be selected by default
    • Submit button label - enter the text that will be shown on the submit button.

Editing the HTML or CSS of the calculator

Editing the shipping calculator HTML

You can edit the HTML code for your shipping rates calculator to make more advanced customizations.

  1. From your Shopify admin, go to Online Store > Themes.
  2. Find the theme you want to edit, and then click Actions > Edit code.
  3. In the Snippets directory, click shipping-calculator.liquid.
  4. Edit the code as needed. You can add new classes and move the existing HTML elements around in the file to suit your needs.

    Note: Do not edit the HTML ID attributes or the class name "get-rates" on the shipping calculator submit button, as this will interfere with functionality.

  5. Click Save.

Editing the shipping calculator CSS

If you want to change the appearance of your shipping rates calculator, then you can add some CSS to your theme stylesheet.

  1. From your Shopify admin, go to Online Store > Themes.
  2. Find the theme you want to edit, and then click Actions > Edit code.
  3. In the Assets directory, click theme.scss.liquid.
  4. At the very bottom of the file, add either the contents of this CSS file, or your own custom CSS code.
  5. Click Save.

Troubleshooting

Updating older themes to use a supported version of jQuery

If you are having trouble getting the shipping calculator to work, then check to confirm that your theme is using a jQuery version of 1.7 or newer. If your theme is running a version of jQuery that is older than 1.7, then you can edit your theme code to use a supported version instead.

  1. In the Layout directory, click theme.liquid.
  2. Within the <head> element, find a script tag that references your theme's jQuery source. The src attribute for the script tag contains a URL that includes /jquery/, followed by the version number. The tag looks something like this:

    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    In the script tag above, the jQuery version being used is 1.4.2. This is an older version of jQuery that will need to be updated for the customization to work. If your theme is using a version that is older than 1.7, replace the version number in the URL with 1.7. The result should look like this:

    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
  3. Click Save.

Demo store

This demo shop has a shipping rates calculator on the cart page.

TyW | Online Community Manager @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit the Shopify Help Center or the Shopify Blog

kabobmaster
Tourist
4 0 2

Hi Ty,

 

I have been able to add the calculator to my cart but it doesn't do anything when the Calculate Shipping button is clicked. Any way you can help me figure out what is going on?

 

Thanks!

Voltage_Matt
Shopify Expert
54 0 21

I just set this up for a client and followed the guide, he is on an older theme without the vendor.js and the button did not work either (javascript not firing correctly).

What I did to solve it. Instead of adding both of those javscript snippets/code into the top & bottom of the theme.js (or vendor.js) I added them to the very bottom of my theme.liquid right before the closing </body> tag. 

Here is what I added:

{% if template contains 'cart' %}
<script>
/**
 * Module to add a shipping rates calculator to cart page.
 *
 * Copyright (c) 2011-2016 Caroline Schnapp (11heavens.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Modified by David Little, 2016
 */

"object"==typeof Countries&&(Countries.updateProvinceLabel=function(e,t){if("string"==typeof e&&Countries[e]&&Countries[e].provinces){if("object"!=typeof t&&(t=document.getElementById("address_province_label"),null===t))return;t.innerHTML=Countries[e].label;var r=jQuery(t).parent();r.find("select");r.find(".custom-style-select-box-inner").html(Countries[e].provinces[0])}}),"undefined"==typeof Shopify.Cart&&(Shopify.Cart={}),Shopify.Cart.ShippingCalculator=function(){var _config={submitButton:"Calculate shipping",submitButtonDisabled:"Calculating...",templateId:"shipping-calculator-response-template",wrapperId:"wrapper-response",customerIsLoggedIn:!1,moneyFormat:"${{amount}}"},_render=function(e){var t=jQuery("#"+_config.templateId),r=jQuery("#"+_config.wrapperId);if(t.length&&r.length){var templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var n=Handlebars.compile(jQuery.trim(t.text())),a=n(e);if(jQuery(a).appendTo(r),"undefined"!=typeof Currency&&"function"==typeof Currency.convertAll){var i="";jQuery("[name=currencies]").size()?i=jQuery("[name=currencies]").val():jQuery("#currencies span.selected").size()&&(i=jQuery("#currencies span.selected").attr("data-currency")),""!==i&&Currency.convertAll(shopCurrency,i,"#wrapper-response span.money, #estimated-shipping span.money")}}},_enableButtons=function(){jQuery(".get-rates").removeAttr("disabled").removeClass("disabled").val(_config.submitButton)},_disableButtons=function(){jQuery(".get-rates").val(_config.submitButtonDisabled).attr("disabled","disabled").addClass("disabled")},_getCartShippingRatesForDestination=function(e){var t={type:"POST",url:"/cart/prepare_shipping_rates",data:jQuery.param({shipping_address:e}),success:_pollForCartShippingRatesForDestination(e),error:_onError};jQuery.ajax(t)},_pollForCartShippingRatesForDestination=function(e){var t=function(){jQuery.ajax("/cart/async_shipping_rates",{dataType:"json",success:function(r,n,a){200===a.status?_onCartShippingRatesUpdate(r.shipping_rates,e):setTimeout(t,500)},error:_onError})};return t},_fullMessagesFromErrors=function(e){var t=[];return jQuery.each(e,function(e,r){jQuery.each(r,function(r,n){t.push(e+" "+n)})}),t},_onError=function(XMLHttpRequest,textStatus){jQuery("#estimated-shipping").hide(),jQuery("#estimated-shipping em").empty(),_enableButtons();var feedback="",data=eval("("+XMLHttpRequest.responseText+")");feedback=data.message?data.message+"("+data.status+"): "+data.description:"Error : "+_fullMessagesFromErrors(data).join("; ")+".","Error : country is not supported."===feedback&&(feedback="We do not ship to this destination."),_render({rates:[],errorFeedback:feedback,success:!1}),jQuery("#"+_config.wrapperId).show()},_onCartShippingRatesUpdate=function(e,t){_enableButtons();var r="";if(t.zip&&(r+=t.zip+", "),t.province&&(r+=t.province+", "),r+=t.country,e.length){"0.00"==e[0].price?jQuery("#estimated-shipping em").html("FREE"):jQuery("#estimated-shipping em").html(_formatRate(e[0].price));for(var n=0;n<e.length;n++)e[n].price=_formatRate(e[n].price)}_render({rates:e,address:r,success:!0}),jQuery("#"+_config.wrapperId+", #estimated-shipping").fadeIn()},_formatRate=function(e){function t(e,t){return"undefined"==typeof e?t:e}function r(e,r,n,a){if(r=t(r,2),n=t(n,","),a=t(a,"."),isNaN(e)||null==e)return 0;e=(e/100).toFixed(r);var i=e.split("."),o=i[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+n),s=i[1]?a+i[1]:"";return o+s}if("function"==typeof Shopify.formatMoney)return Shopify.formatMoney(e,_config.moneyFormat);"string"==typeof e&&(e=e.replace(".",""));var n="",a=/\{\{\s*(\w+)\s*\}\}/,i=_config.moneyFormat;switch(i.match(a)[1]){case"amount":n=r(e,2);break;case"amount_no_decimals":n=r(e,0);break;case"amount_with_comma_separator":n=r(e,2,".",",");break;case"amount_no_decimals_with_comma_separator":n=r(e,0,".",",")}return i.replace(a,n)};return _init=function(){new Shopify.CountryProvinceSelector("address_country","address_province",{hideElement:"address_province_container"});var e=jQuery("#address_country"),t=jQuery("#address_province_label").get(0);"undefined"!=typeof Countries&&(Countries.updateProvinceLabel(e.val(),t),e.change(function(){Countries.updateProvinceLabel(e.val(),t)})),jQuery(".get-rates").click(function(){_disableButtons(),jQuery("#"+_config.wrapperId).empty().hide();var e={};e.zip=jQuery("#address_zip").val()||"",e.country=jQuery("#address_country").val()||"",e.province=jQuery("#address_province").val()||"",_getCartShippingRatesForDestination(e)}),_config.customerIsLoggedIn&&jQuery(".get-rates:eq(0)").trigger("click")},{show:function(e){e=e||{},jQuery.extend(_config,e),jQuery(function(){_init()})},getConfig:function(){return _config},formatRate:function(e){return _formatRate(e)}}}();

// Shipping Calculator continued
Shopify.Cart.ShippingCalculator.show( {
  submitButton: theme.strings.shippingCalcSubmitButton,
  submitButtonDisabled: theme.strings.shippingCalcSubmitButtonDisabled,
  customerIsLoggedIn: theme.strings.shippingCalcCustomerIsLoggedIn,
  moneyFormat: theme.strings.shippingCalcMoneyFormat
} );
</script>
{% endif %}

 

Screen Shot 2020-01-31 at 11.28.04 AM.png

Make sure you remove the code from the vendor.js or the theme.js.

 

Andy_Storey1
Tourist
9 0 4

Hi all.

 

Has anybody had any luck on getting the shipping rates calculator to work with Shopify's Multi-Currency feature?

(I know it says it doesn't work)

 

We get 1-2 emails per week saying the rates are wrong.    It is because the shipping rates calculator puts the current currency symbol next to rates[i].price, but does not carry out any conversion.

 

<ul id="shipping-rates">
<% for (var i=0; i<rates.length; i++) { %>
<li><%= rates[i].name %> {{ 'cart.shipping_calculator.at' | t }} <%= rates[i].price %></li>
<% } %>
</ul>

 

Thanks

Andy

Andy_Storey1
Tourist
9 0 4

In the short-term, I opted to use regex to remove the user currency settings and just output using the store's currency - in my case GBP.

 

<li><%= rates[i].name %> {{ 'cart.shipping_calculator.at' | t }} &pound;<%= regex.exec(rates[i].price) %> GBP</li>

 

Would still like to do it properly though!

SarahJ22
New Member
2 0 0

Thank you for posting this, I found it very easy to implement and it was a great enhancement to my cart at:

www.lime-at.com/cart

However, after months of working really well, it suddenly stopped for no reason and only the following text was appearing:

"Rates start at £13.00 GBP."

I followed the instructions again, overwriting the existing code, and now have:

"Rates start at £13.00 GBP.

Rates start at £13.00 GBP."


I wonder if Shopify have made any changes that would have stopped this working?


I'm really missing it 😞

 

Thanks again,

Sarah

kineticdev
Shopify Partner
1 0 0

 Please delete

 

PurpleMamba
Shopify Partner
114 2 16

Thanks for this! I've set it up on an older non-sectioned theme and it works great!

 

However, I have a problem on a sectioned theme.

 

I get this error: "Uncaught ReferenceError: theme is not defined" for this code:

 

<script>
  theme.strings = {
    shippingCalcSubmitButton: "Calculate shipping",
    shippingCalcSubmitButtonDisabled: "Calculating...",
    shippingCalcMoneyFormat: "\u003cspan class=money\u003e${{amount}} USD\u003c\/span\u003e"
  }
</script>

Any suggestions to fix this?

GoodFy_Brasil
Explorer
65 1 3

@kabobmaster wrote:

Hi Ty,

 

I have been able to add the calculator to my cart but it doesn't do anything when the Calculate Shipping button is clicked. Any way you can help me figure out what is going on?

 

Thanks!


Hey @kabobmaster  did you solve this ?  I just followed the instructions and has worked perfectly ... let us know what did you get and what Theme are you using 

William Alencar
GoodFy Brasil
GoodFy_Brasil
Explorer
65 1 3

@Voltage_Matt wrote:

I just set this up for a client and followed the guide, he is on an older theme without the vendor.js and the button did not work either (javascript not firing correctly).

What I did to solve it. Instead of adding both of those javscript snippets/code into the top & bottom of the theme.js (or vendor.js) I added them to the very bottom of my theme.liquid right before the closing </body> tag. 

Here is what I added:

{% if template contains 'cart' %}
<script>
/**
 * Module to add a shipping rates calculator to cart page.
 *
 * Copyright (c) 2011-2016 Caroline Schnapp (11heavens.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Modified by David Little, 2016
 */

"object"==typeof Countries&&(Countries.updateProvinceLabel=function(e,t){if("string"==typeof e&&Countries[e]&&Countries[e].provinces){if("object"!=typeof t&&(t=document.getElementById("address_province_label"),null===t))return;t.innerHTML=Countries[e].label;var r=jQuery(t).parent();r.find("select");r.find(".custom-style-select-box-inner").html(Countries[e].provinces[0])}}),"undefined"==typeof Shopify.Cart&&(Shopify.Cart={}),Shopify.Cart.ShippingCalculator=function(){var _config={submitButton:"Calculate shipping",submitButtonDisabled:"Calculating...",templateId:"shipping-calculator-response-template",wrapperId:"wrapper-response",customerIsLoggedIn:!1,moneyFormat:"${{amount}}"},_render=function(e){var t=jQuery("#"+_config.templateId),r=jQuery("#"+_config.wrapperId);if(t.length&&r.length){var templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var n=Handlebars.compile(jQuery.trim(t.text())),a=n(e);if(jQuery(a).appendTo(r),"undefined"!=typeof Currency&&"function"==typeof Currency.convertAll){var i="";jQuery("[name=currencies]").size()?i=jQuery("[name=currencies]").val():jQuery("#currencies span.selected").size()&&(i=jQuery("#currencies span.selected").attr("data-currency")),""!==i&&Currency.convertAll(shopCurrency,i,"#wrapper-response span.money, #estimated-shipping span.money")}}},_enableButtons=function(){jQuery(".get-rates").removeAttr("disabled").removeClass("disabled").val(_config.submitButton)},_disableButtons=function(){jQuery(".get-rates").val(_config.submitButtonDisabled).attr("disabled","disabled").addClass("disabled")},_getCartShippingRatesForDestination=function(e){var t={type:"POST",url:"/cart/prepare_shipping_rates",data:jQuery.param({shipping_address:e}),success:_pollForCartShippingRatesForDestination(e),error:_onError};jQuery.ajax(t)},_pollForCartShippingRatesForDestination=function(e){var t=function(){jQuery.ajax("/cart/async_shipping_rates",{dataType:"json",success:function(r,n,a){200===a.status?_onCartShippingRatesUpdate(r.shipping_rates,e):setTimeout(t,500)},error:_onError})};return t},_fullMessagesFromErrors=function(e){var t=[];return jQuery.each(e,function(e,r){jQuery.each(r,function(r,n){t.push(e+" "+n)})}),t},_onError=function(XMLHttpRequest,textStatus){jQuery("#estimated-shipping").hide(),jQuery("#estimated-shipping em").empty(),_enableButtons();var feedback="",data=eval("("+XMLHttpRequest.responseText+")");feedback=data.message?data.message+"("+data.status+"): "+data.description:"Error : "+_fullMessagesFromErrors(data).join("; ")+".","Error : country is not supported."===feedback&&(feedback="We do not ship to this destination."),_render({rates:[],errorFeedback:feedback,success:!1}),jQuery("#"+_config.wrapperId).show()},_onCartShippingRatesUpdate=function(e,t){_enableButtons();var r="";if(t.zip&&(r+=t.zip+", "),t.province&&(r+=t.province+", "),r+=t.country,e.length){"0.00"==e[0].price?jQuery("#estimated-shipping em").html("FREE"):jQuery("#estimated-shipping em").html(_formatRate(e[0].price));for(var n=0;n<e.length;n++)e[n].price=_formatRate(e[n].price)}_render({rates:e,address:r,success:!0}),jQuery("#"+_config.wrapperId+", #estimated-shipping").fadeIn()},_formatRate=function(e){function t(e,t){return"undefined"==typeof e?t:e}function r(e,r,n,a){if(r=t(r,2),n=t(n,","),a=t(a,"."),isNaN(e)||null==e)return 0;e=(e/100).toFixed(r);var i=e.split("."),o=i[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+n),s=i[1]?a+i[1]:"";return o+s}if("function"==typeof Shopify.formatMoney)return Shopify.formatMoney(e,_config.moneyFormat);"string"==typeof e&&(e=e.replace(".",""));var n="",a=/\{\{\s*(\w+)\s*\}\}/,i=_config.moneyFormat;switch(i.match(a)[1]){case"amount":n=r(e,2);break;case"amount_no_decimals":n=r(e,0);break;case"amount_with_comma_separator":n=r(e,2,".",",");break;case"amount_no_decimals_with_comma_separator":n=r(e,0,".",",")}return i.replace(a,n)};return _init=function(){new Shopify.CountryProvinceSelector("address_country","address_province",{hideElement:"address_province_container"});var e=jQuery("#address_country"),t=jQuery("#address_province_label").get(0);"undefined"!=typeof Countries&&(Countries.updateProvinceLabel(e.val(),t),e.change(function(){Countries.updateProvinceLabel(e.val(),t)})),jQuery(".get-rates").click(function(){_disableButtons(),jQuery("#"+_config.wrapperId).empty().hide();var e={};e.zip=jQuery("#address_zip").val()||"",e.country=jQuery("#address_country").val()||"",e.province=jQuery("#address_province").val()||"",_getCartShippingRatesForDestination(e)}),_config.customerIsLoggedIn&&jQuery(".get-rates:eq(0)").trigger("click")},{show:function(e){e=e||{},jQuery.extend(_config,e),jQuery(function(){_init()})},getConfig:function(){return _config},formatRate:function(e){return _formatRate(e)}}}();

// Shipping Calculator continued
Shopify.Cart.ShippingCalculator.show( {
  submitButton: theme.strings.shippingCalcSubmitButton,
  submitButtonDisabled: theme.strings.shippingCalcSubmitButtonDisabled,
  customerIsLoggedIn: theme.strings.shippingCalcCustomerIsLoggedIn,
  moneyFormat: theme.strings.shippingCalcMoneyFormat
} );
</script>
{% endif %}

 

Screen Shot 2020-01-31 at 11.28.04 AM.png

Make sure you remove the code from the vendor.js or the theme.js.

 


I will try this as using vendor.js and theme.js I face the same problem ...

the calculator is rendered but button did not display anything... 

Lets see

William Alencar
GoodFy Brasil
GoodFy_Brasil
Explorer
65 1 3

@GoodFy_Brasil wrote:

@Voltage_Matt wrote:

I just set this up for a client and followed the guide, he is on an older theme without the vendor.js and the button did not work either (javascript not firing correctly).

What I did to solve it. Instead of adding both of those javscript snippets/code into the top & bottom of the theme.js (or vendor.js) I added them to the very bottom of my theme.liquid right before the closing </body> tag. 

Here is what I added:

{% if template contains 'cart' %}
<script>
/**
 * Module to add a shipping rates calculator to cart page.
 *
 * Copyright (c) 2011-2016 Caroline Schnapp (11heavens.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Modified by David Little, 2016
 */

"object"==typeof Countries&&(Countries.updateProvinceLabel=function(e,t){if("string"==typeof e&&Countries[e]&&Countries[e].provinces){if("object"!=typeof t&&(t=document.getElementById("address_province_label"),null===t))return;t.innerHTML=Countries[e].label;var r=jQuery(t).parent();r.find("select");r.find(".custom-style-select-box-inner").html(Countries[e].provinces[0])}}),"undefined"==typeof Shopify.Cart&&(Shopify.Cart={}),Shopify.Cart.ShippingCalculator=function(){var _config={submitButton:"Calculate shipping",submitButtonDisabled:"Calculating...",templateId:"shipping-calculator-response-template",wrapperId:"wrapper-response",customerIsLoggedIn:!1,moneyFormat:"${{amount}}"},_render=function(e){var t=jQuery("#"+_config.templateId),r=jQuery("#"+_config.wrapperId);if(t.length&&r.length){var templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var n=Handlebars.compile(jQuery.trim(t.text())),a=n(e);if(jQuery(a).appendTo(r),"undefined"!=typeof Currency&&"function"==typeof Currency.convertAll){var i="";jQuery("[name=currencies]").size()?i=jQuery("[name=currencies]").val():jQuery("#currencies span.selected").size()&&(i=jQuery("#currencies span.selected").attr("data-currency")),""!==i&&Currency.convertAll(shopCurrency,i,"#wrapper-response span.money, #estimated-shipping span.money")}}},_enableButtons=function(){jQuery(".get-rates").removeAttr("disabled").removeClass("disabled").val(_config.submitButton)},_disableButtons=function(){jQuery(".get-rates").val(_config.submitButtonDisabled).attr("disabled","disabled").addClass("disabled")},_getCartShippingRatesForDestination=function(e){var t={type:"POST",url:"/cart/prepare_shipping_rates",data:jQuery.param({shipping_address:e}),success:_pollForCartShippingRatesForDestination(e),error:_onError};jQuery.ajax(t)},_pollForCartShippingRatesForDestination=function(e){var t=function(){jQuery.ajax("/cart/async_shipping_rates",{dataType:"json",success:function(r,n,a){200===a.status?_onCartShippingRatesUpdate(r.shipping_rates,e):setTimeout(t,500)},error:_onError})};return t},_fullMessagesFromErrors=function(e){var t=[];return jQuery.each(e,function(e,r){jQuery.each(r,function(r,n){t.push(e+" "+n)})}),t},_onError=function(XMLHttpRequest,textStatus){jQuery("#estimated-shipping").hide(),jQuery("#estimated-shipping em").empty(),_enableButtons();var feedback="",data=eval("("+XMLHttpRequest.responseText+")");feedback=data.message?data.message+"("+data.status+"): "+data.description:"Error : "+_fullMessagesFromErrors(data).join("; ")+".","Error : country is not supported."===feedback&&(feedback="We do not ship to this destination."),_render({rates:[],errorFeedback:feedback,success:!1}),jQuery("#"+_config.wrapperId).show()},_onCartShippingRatesUpdate=function(e,t){_enableButtons();var r="";if(t.zip&&(r+=t.zip+", "),t.province&&(r+=t.province+", "),r+=t.country,e.length){"0.00"==e[0].price?jQuery("#estimated-shipping em").html("FREE"):jQuery("#estimated-shipping em").html(_formatRate(e[0].price));for(var n=0;n<e.length;n++)e[n].price=_formatRate(e[n].price)}_render({rates:e,address:r,success:!0}),jQuery("#"+_config.wrapperId+", #estimated-shipping").fadeIn()},_formatRate=function(e){function t(e,t){return"undefined"==typeof e?t:e}function r(e,r,n,a){if(r=t(r,2),n=t(n,","),a=t(a,"."),isNaN(e)||null==e)return 0;e=(e/100).toFixed(r);var i=e.split("."),o=i[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+n),s=i[1]?a+i[1]:"";return o+s}if("function"==typeof Shopify.formatMoney)return Shopify.formatMoney(e,_config.moneyFormat);"string"==typeof e&&(e=e.replace(".",""));var n="",a=/\{\{\s*(\w+)\s*\}\}/,i=_config.moneyFormat;switch(i.match(a)[1]){case"amount":n=r(e,2);break;case"amount_no_decimals":n=r(e,0);break;case"amount_with_comma_separator":n=r(e,2,".",",");break;case"amount_no_decimals_with_comma_separator":n=r(e,0,".",",")}return i.replace(a,n)};return _init=function(){new Shopify.CountryProvinceSelector("address_country","address_province",{hideElement:"address_province_container"});var e=jQuery("#address_country"),t=jQuery("#address_province_label").get(0);"undefined"!=typeof Countries&&(Countries.updateProvinceLabel(e.val(),t),e.change(function(){Countries.updateProvinceLabel(e.val(),t)})),jQuery(".get-rates").click(function(){_disableButtons(),jQuery("#"+_config.wrapperId).empty().hide();var e={};e.zip=jQuery("#address_zip").val()||"",e.country=jQuery("#address_country").val()||"",e.province=jQuery("#address_province").val()||"",_getCartShippingRatesForDestination(e)}),_config.customerIsLoggedIn&&jQuery(".get-rates:eq(0)").trigger("click")},{show:function(e){e=e||{},jQuery.extend(_config,e),jQuery(function(){_init()})},getConfig:function(){return _config},formatRate:function(e){return _formatRate(e)}}}();

// Shipping Calculator continued
Shopify.Cart.ShippingCalculator.show( {
  submitButton: theme.strings.shippingCalcSubmitButton,
  submitButtonDisabled: theme.strings.shippingCalcSubmitButtonDisabled,
  customerIsLoggedIn: theme.strings.shippingCalcCustomerIsLoggedIn,
  moneyFormat: theme.strings.shippingCalcMoneyFormat
} );
</script>
{% endif %}

 

Screen Shot 2020-01-31 at 11.28.04 AM.png

Make sure you remove the code from the vendor.js or the theme.js.

 


I will try this as using vendor.js and theme.js I face the same problem ...

the calculator is rendered but button did not display anything... 

Lets see


Not working for a NON Shopify Theme ... still need to check why ... as for FREE SHOPIFY THEME has worked 

William Alencar
GoodFy Brasil
kabobmaster
Tourist
4 0 2

I have not been able to solve this. I am currently using Shopify's Debut theme. I had a Shopify expert help me but they did not get it working. All they did was place all of the github code in the cart-template.liquid

 

When the button is pressed, it displays "Calculating..." but returns without results and the button text reads "Calculate Shipping" again. 

 

Also it might be helpful to note that I am using a shipping calculator app called Intuitive Shipping. I was also using Advanced Shipping Rules prior and with both shipping apps the calculator would not work.

GoodFy_Brasil
Explorer
65 1 3

@kabobmaster wrote:

I have not been able to solve this. I am currently using Shopify's Debut theme. I had a Shopify expert help me but they did not get it working. All they did was place all of the github code in the cart-template.liquid

 

When the button is pressed, it displays "Calculating..." but returns without results and the button text reads "Calculate Shipping" again. 

 

Also it might be helpful to note that I am using a shipping calculator app called Intuitive Shipping. I was also using Advanced Shipping Rules prior and with both shipping apps the calculator would not work.


Ok ... I will try this in DEBUT Theme ...

If you watn you can share me an admin staff account so I can take a look in your store .

My email is william@beautylet.com.br

Best Regards 

William Alencar
GoodFy Brasil
PurpleMamba
Shopify Partner
114 2 16
Troubleshooting

 

Depending on your theme and currency settings, you might see your shipping calculator price estimates displayed on the cart page with un-rendered HTML tags:

 

calc03.jpg

 

To remove these unwanted tags, you will need to make a change to your currency settings in the admin.

 

  1. From your Shopify admin, go to Settings > General.
  2. In the Store currency section, your shop currency is listed. Click Change formatting.
  3. Remove the HTML tags from your currency formats. By default, the settings look like this:

    calc05.jpg
    From both the HTML with currency and the HTML without currency text fields, remove the opening and closing HTML span tags. The result should look like this:

    calc06.jpg
  4. Click Save.

Your shipping calculator price estimates should now display without un-rendered HTML tags:


fixed-70db803ad9ededd688c22ab2bc0e161efde4c99e6996631605e5364d02b9229f.jpg

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Do NOT change your store's currency settings as described here as this will break any currency selector you might have installed in your store.

 

Make sure to keep your store's currency settings WITH the span class tags, like this example:

HTML with currency: <span class=money>${{amount}} USD</span>

HTML without currency: <span class=money>${{amount}}</span>

 

To fix the issue where the span class appears in the shipping calculator rates estimates, go into the shipping-calulator.liquid snippet you made earlier and find {{price}} (with double curly braces), and change that to {{{price}}} (with triple curly braces).

PurpleMamba
Shopify Partner
114 2 16

@TyW wrote:

 

Troubleshooting

 

 

Depending on your theme and currency settings, you might see your shipping calculator price estimates displayed on the cart page with un-rendered HTML tags:

 

calc03.jpg

 

To remove these unwanted tags, you will need to make a change to your currency settings in the admin.

 

  1. From your Shopify admin, go to Settings > General.
  2. In the Store currency section, your shop currency is listed. Click Change formatting.
  3. Remove the HTML tags from your currency formats. By default, the settings look like this:

    calc05.jpg
    From both the HTML with currency and the HTML without currency text fields, remove the opening and closing HTML span tags. The result should look like this:

    calc06.jpg
  4. Click Save.

Your shipping calculator price estimates should now display without un-rendered HTML tags:


fixed-70db803ad9ededd688c22ab2bc0e161efde4c99e6996631605e5364d02b9229f.jpg

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 




 

Do NOT change your currency settings as described here in the "Sectioned Themes" post, as this will break any currency selector you might have installed in your store.

 

Make sure to keep your store's currency settings WITH the span class tags, like this example:

HTML with currency: <span class=money>${{amount}} USD</span>

HTML without currency: <span class=money>${{amount}}</span>

 

To fix the issue where the span class appears in the shipping calculator rates estimates, go into the shipping-calculator.liquid snippet you made earlier and find {{price}} (with double curly braces). Change that to {{{price}}} (with triple curly braces). ( In Handlebars, which this script uses for this part, {{price}} is HTML-escaped, but {{{price}}} is not.)

PurpleMamba
Shopify Partner
114 2 16

Do NOT change your currency settings as described in the "Sectioned Themes" post, as this will break any currency selector you might have installed in your store.

 

Make sure to keep your store's currency settings WITH the span class tags, like this example:

HTML with currency: <span class=money>${{amount}} USD</span>

HTML without currency: <span class=money>${{amount}}</span>

 

To fix the issue where the span class appears in the shipping calculator rates estimates:

Go into the shipping-calculator.liquid snippet you made earlier and find {{price}} (with double curly braces). 

Change that to {{{price}}} (with triple curly braces). 

(In Handlebars, which this snippet uses, {{price}} will be HTML-escaped, but {{{price}}} will not.)

Jeansilva
New Member
1 0 0
ogeid
Shopify Partner
67 0 21

This is great. Followed your steps and it works. Thanks for positing.

 

Is there are way to show all shipping option.?

 

Also, any suggestion on how we can add a tax estimate as well?

 

Thanks, Diego

D.E.W. L.A. - Web Design
https://dew.la