Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to hide and show payment gateways in shopify checkout (COD)
var CODGatewayName = "Cash on Delivery",
CODShippingName = "Cash on delivery",
radioButtonSelector = ".radio__input .input-radio";
function toggleCODPayment(shippingElement) {
var isCOD = function(el) {
return el.querySelectorAll(".radio__label__primary")[0] && el.querySelectorAll(".radio__label__primary")[0].textContent.trim().toLowerCase().indexOf(CODGatewayName.toLowerCase()) != -1;
}
if (shippingElement && shippingElement.textContent.trim().toLowerCase().indexOf(CODShippingName.toLowerCase()) > -1) {
var els = document.querySelectorAll(".section--payment-method .radio-wrapper.content-box__row");
for (var i = 0; i < els.length; i++) {
var el = els[i],
radioButton = el.querySelector(radioButtonSelector);
if (el.dataset.selectGateway && !isCOD(el)) {
el.classList.add("visually-hidden");
document.getElementById("payment-gateway-subfields-" + el.dataset.selectGateway).classList.add("visually-hidden");
if (radioButton.checked) {
radioButton.checked = false;
}
} else if (el.dataset.selectGateway && isCOD(el)) {
radioButton.click();
}
}
} else if (shippingElement) {
var els = document.querySelectorAll(".section--payment-method .radio-wrapper.content-box__row"),
radioButtons = [];
for (var i = 0; i < els.length; i++) {
var el = els[i],
radioButton = el.querySelector(radioButtonSelector);
if (el.dataset.selectGateway && isCOD(el)) {
el.classList.add("visually-hidden");
document.getElementById("payment-gateway-subfields-" + el.dataset.selectGateway).classList.add("visually-hidden");
if (radioButton.checked) {
radioButton.checked = false;
}
} else if (radioButton && el.dataset.selectGateway) {
radioButtons.push(radioButton);
}
}
if (!radioButtons.reduce(function(checked, el) { return checked || el.checked }, false)) {
radioButtons[0].click();
}
}
}
function initObserver(shippingElement) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.target == document.querySelector(".main__content")) { toggleCODPayment(shippingElement) }
});
});
observer.observe(document.querySelector(".main"), {childList: true, subtree: true});
}
(function(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();})(function(){
var shippingElement = document.querySelector("div.review-block:nth-child(3) > div:nth-child(1) > div:nth-child(2)");
if (shippingElement) {
initObserver(shippingElement);
toggleCODPayment(shippingElement);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment