Last active
August 29, 2015 14:19
-
-
Save raekul/65befc66888b7e0f763b to your computer and use it in GitHub Desktop.
[Shopify] Combine all variant quantities from product json.
This file contains 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
(function($) { | |
// get json data from product | |
var totalStock = function(json, selector) { | |
// caching | |
var $el = typeof(selector) ? $(selector) : 'undefined', | |
i = 0, | |
qty = 0, | |
product_json = json, | |
variant, | |
variants, | |
threshold; | |
for (i ; i < product_json.length ; i++) { | |
// grab the current product and it's variants | |
variants = product_json[i].variants; | |
// for every variant total overall quantities | |
variant = variants.every(function(value, index, arr){ | |
qty += value.inventory_quantity; | |
if (value >= threshold) { | |
return false; | |
} | |
return true; | |
}); | |
// append the total quantity into the element | |
$($el[i]).append('x '+qty); | |
// reset the qty to zero so we aren't just incrementing | |
// the last value set | |
qty = 0; | |
} | |
return; | |
}; | |
// totalStock takes two arguments | |
// First argument is the collection of products you want to get, or all etc | |
// Second is the selector that you want the total quantity to appear in | |
$(document).ready( totalStock({{ collections[settings.frontpage_collection].products | json }}, $('.product__available') ) ); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment