Skip to content

Instantly share code, notes, and snippets.

@DenisLeblanc
Forked from atikju/StockChanger.liquid
Created November 14, 2023 04:26
Show Gist options
  • Save DenisLeblanc/165a00ac4759bba73d27fa08b29587a5 to your computer and use it in GitHub Desktop.
Save DenisLeblanc/165a00ac4759bba73d27fa08b29587a5 to your computer and use it in GitHub Desktop.
Show Stock Quantity in Product Page - Shopify
<div id="variant-inventory" class="devst-variant-inventory">
{% if product.variants.first.inventory_management == "shopify" %}
{% if product.variants.first.inventory_quantity > 0 %}
Only <span class="devStock">{{ product.variants.first.inventory_quantity }}</span> left!
{% else %}
The product is out of stock
{% endif %}
{% else %}
This product is available
{% endif %}
</div>
{% comment %} this code goes at the footer {% endcomment %}
{% if template.name == 'product' %}
{{ 'option_selection.js' | shopify_asset_url | script_tag }}
<style>
.selector-wrapper {
display: none !important;
}
</style>
<script>
var selectCallback = function(variant, selector) {
if (variant) {
if (variant.available) {
$('.devStock').text(variant.inventory_quantity);
console.log('yo: '+variant.inventory_quantity);
// Selected a valid variant that is available.
//$('#add').removeClass('disabled').removeAttr('disabled').val('Add to Cart').fadeTo(200,1);
} else {
// Variant is sold out.
$('.devStock').text(variant.inventory_quantity);
}
} else {
// variant doesn't exist.
$('#add').val('Unavailable').addClass('disabled').attr('disabled', 'disabled').fadeTo(200,0.5);
}
}
// initialize multi selector for product
jQuery(function($) {
new Shopify.OptionSelectors("product-select", { product: {{ product | json }}, onVariantSelected: selectCallback });
$('.option-value-input').on('change', function(){
setTimeout(function(){
var currentVar = location.href;
currentVar = currentVar.split('=')[1];
prodGetter(currentVar);
}, 300);
});
var product_handle = '{{ product.handle }}';
function prodGetter(currentVar){
var disID = currentVar;
jQuery.getJSON('/products/'+product_handle+'.js', function(product) {
var xx = product.variants;
var i;
for (i = 0; i < xx.length; i++) {
var thisIDx = xx[i].id;
if( disID == thisIDx){
console.log(xx[i].inventory_quantity);
$('.devStock').text(xx[i].inventory_quantity);
}
}
});
}
});
</script>
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment