| 1 |
/** |
| 2 |
* Merchant custom add to cart button. |
| 3 |
* |
| 4 |
*/ |
| 5 |
|
| 6 |
'use strict'; |
| 7 |
|
| 8 |
var merchant = merchant || {}; |
| 9 |
merchant.customAddToCartButton = { |
| 10 |
domReady: function domReady(fn) { |
| 11 |
if (typeof fn !== 'function') { |
| 12 |
return; |
| 13 |
} |
| 14 |
if (document.readyState === 'interactive' || document.readyState === 'complete') { |
| 15 |
return fn(); |
| 16 |
} |
| 17 |
document.addEventListener('DOMContentLoaded', fn, false); |
| 18 |
}, |
| 19 |
init: function init() { |
| 20 |
var button = document.querySelectorAll('.merchant-custom-addtocart'); |
| 21 |
if (!button.length) { |
| 22 |
return false; |
| 23 |
} |
| 24 |
for (var i = 0; i < button.length; i++) { |
| 25 |
button[i].addEventListener('click', function (e) { |
| 26 |
e.preventDefault(); |
| 27 |
var button = this, |
| 28 |
productId = this.getAttribute('data-product-id'), |
| 29 |
initial_text = this.innerHTML, |
| 30 |
loading_text = this.getAttribute('data-loading-text'), |
| 31 |
added_text = this.getAttribute('data-added-text'), |
| 32 |
nonce = this.getAttribute('data-nonce'); |
| 33 |
var ajax = new XMLHttpRequest(); |
| 34 |
ajax.open('POST', merchant.setting.ajax_url, true); |
| 35 |
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); |
| 36 |
button.innerHTML = loading_text; |
| 37 |
ajax.onload = function () { |
| 38 |
if (this.status >= 200 && this.status < 400) { |
| 39 |
button.innerHTML = added_text; |
| 40 |
setTimeout(function () { |
| 41 |
button.innerHTML = initial_text; |
| 42 |
}, 1500); |
| 43 |
jQuery(document.body).trigger('wc_fragment_refresh'); |
| 44 |
jQuery(document.body).trigger('added_to_cart', [button, productId]); |
| 45 |
document.body.dispatchEvent(new Event('merchant.custom_added_to_cart')); |
| 46 |
} |
| 47 |
}; |
| 48 |
ajax.send('action=merchant_custom_addtocart&product_id=' + productId + '&nonce=' + nonce); |
| 49 |
}); |
| 50 |
} |
| 51 |
} |
| 52 |
}; |
| 53 |
|
| 54 |
// Initialize. |
| 55 |
merchant.customAddToCartButton.domReady(function () { |
| 56 |
merchant.customAddToCartButton.init(); |
| 57 |
}); |