Last active
October 30, 2018 02:39
-
-
Save drabbytux/9fc44ea0b2151129326cde399863c0ce to your computer and use it in GitHub Desktop.
Shipping cart JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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)}}}(); |
@rogeriolino same for me... can you help @drabbytux ?
I think this one is better.
if(typeof Countries==="object"){Countries.updateProvinceLabel=function(d,a){if(typeof d==="string"&&Countries[d]&&Countries[d].provinces){if(typeof a!=="object"){a=document.getElementById("address_province_label");if(a===null){return}}a.innerHTML=Countries[d].label;var c=$(a).parent();var b=c.find("select");c.find(".custom-style-select-box-inner").html(Countries[d].provinces[0])}}}if(typeof Shopify.Cart==="undefined"){Shopify.Cart={}}Shopify.Cart.ShippingCalculator=(function(){var _config={submitButton:"Calculate shipping",submitButtonDisabled:"Calculating...",templateId:"shipping-calculator-response-template",wrapperId:"wrapper-response",customerIsLoggedIn:false,moneyFormat:"$ {{amount}}"};var _render=function(response){var template=jQuery("#"+_config.templateId);var wrapper=jQuery("#"+_config.wrapperId);if(template.length&&wrapper.length){template.tmpl(response).appendTo(wrapper);if(typeof Currency!=="undefined"&&typeof Currency.convertAll==="function"){var newCurrency="";if(jQuery("[name=currencies]").size()){newCurrency=jQuery("[name=currencies]").val()}else{if(jQuery("#currencies span.selected").size()){newCurrency=jQuery("#currencies span.selected").attr("data-currency")}}if(newCurrency!==""){Currency.convertAll(shopCurrency,newCurrency,"#wrapper-response span.money, #estimated-shipping em span.money")}}}};var _enableButtons=function(){jQuery(".get-rates").removeClass("disabled").val(_config.submitButton)};var _disableButtons=function(){jQuery(".get-rates").val(_config.submitButtonDisabled).addClass("disabled")};var _getCartShippingRatesForDestination=function(shipping_address){var params={type:"GET",url:"/cart/shipping_rates.json",data:jQuery.param({shipping_address:shipping_address}),dataType:"json",success:function(response){rates=response.shipping_rates;_onCartShippingRatesUpdate(rates,shipping_address)},error:function(XMLHttpRequest,textStatus){_onError(XMLHttpRequest,textStatus)}};jQuery.ajax(params)};var _fullMessagesFromErrors=function(errors){var fullMessages=[];jQuery.each(errors,function(attribute,messages){jQuery.each(messages,function(index,message){fullMessages.push(attribute+" "+message)})});return fullMessages};var _onError=function(XMLHttpRequest,textStatus){jQuery("#estimated-shipping").hide();jQuery("#estimated-shipping em").empty();_enableButtons();var feedback="";var data=eval("("+XMLHttpRequest.responseText+")");if(!!data.message){feedback=data.message+"("+data.status+"): "+data.description}else{feedback="Error : "+_fullMessagesFromErrors(data).join("; ")}if(feedback==="Error : country is not supported."){feedback="We do not ship to this destination."}_render({rates:[],errorFeedback:feedback,success:false});jQuery("#"+_config.wrapperId).show()};var _onCartShippingRatesUpdate=function(rates,shipping_address){_enableButtons();var readable_address="";if(shipping_address.zip){readable_address+=shipping_address.zip+", "}if(shipping_address.province){readable_address+=shipping_address.province+", "}readable_address+=shipping_address.country;if(rates.length){if(rates[0].price=="0.00"){jQuery("#estimated-shipping em").html("FREE")}else{jQuery("#estimated-shipping em").html(_formatRate(rates[0].price))}}_render({rates:rates,address:readable_address,success:true});jQuery("#"+_config.wrapperId+", #estimated-shipping").fadeIn()};var _formatRate=function(cents){if(typeof cents=="string"){cents=cents.replace(".","")}var value="";var patt=/\{\{\s*(\w+)\s*\}\}/;var formatString=_config.moneyFormat;function addCommas(moneyString){return moneyString.replace(/(\d+)(\d{3}[\.,]?)/,"$1,$2")}function floatToString(numeric,decimals){var amount=numeric.toFixed(decimals).toString();if(amount.match(/^\.\d+/)){return"0"+amount}else{return amount}}switch(formatString.match(patt)[1]){case"amount":value=addCommas(floatToString(cents/100,2));break;case"amount_no_decimals":value=addCommas(floatToString(cents/100,0));break;case"amount_with_comma_separator":value=floatToString(cents/100,2).replace(/\./,",");break;case"amount_no_decimals_with_comma_separator":value=addCommas(floatToString(cents/100,0)).replace(/\./,",");break}return formatString.replace(patt,value)};_init=function(){new Shopify.CountryProvinceSelector("address_country","address_province",{hideElement:"address_province_container"});var countriesSelect=jQuery("#address_country");var addressProvinceLabelEl=jQuery("#address_province_label").get(0);if(typeof Countries!=="undefined"){Countries.updateProvinceLabel(countriesSelect.val(),addressProvinceLabelEl);countriesSelect.change(function(){Countries.updateProvinceLabel(countriesSelect.val(),addressProvinceLabelEl)})}jQuery('#shipping-calculator').on('click', '.get-rates:not(.disabled)', function() {_disableButtons();jQuery("#"+_config.wrapperId).empty().hide();var shippingAddress={};shippingAddress.zip=jQuery("#address_zip").val()||"";shippingAddress.country=jQuery("#address_country").val()||"";shippingAddress.province=jQuery("#address_province").val()||"";_getCartShippingRatesForDestination(shippingAddress)});if(_config.customerIsLoggedIn){jQuery(".get-rates:eq(0)").trigger("click")}};return{show:function(params){params=params||{};jQuery.extend(_config,params);jQuery(function(){_init()})},getConfig:function(){return _config},formatRate:function(cents){return _formatRate(cents)}}})();
Hi, after installing the shipping calculator my product swatches stopped working. If I turn if off and use the dropdown menu it works correctly. Any idea how to fix? Thanks!
This is the tutorial I followed for the swatches: https://help.shopify.com/en/themes/customization/products/features/add-color-swatches
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm getting
Shopify.CountryProvinceSelector is not a constructor
error outside cart page.