Using JS to modify add to cart based on stock status

DOB
Tourist
10 0 2

Hey everyone -

I'm trying to split our warehouse locations for international commerce so that if something is out of stock at the nearest location the add to cart button is disabled for a user. Shopify uses the total inventory level to determine whether to mark something as sold out on the front end, and we are not going to open multiple stores or use an app that creates hundreds of variants just to solve this one issue.

Instead I have found a nice little third-party app that will display our product inventory information on the front-end (split by warehouse and the message changes based on geolocation).

The only issue is that I would like for it to change both our add to cart button message as well as disabling the button, and so now all I need to do is modify a bit of JS that will search for the "out of stock" class the app generates, and modify the add to cart button if it finds it.

The <span> that is created when something is out of stock has a unique class: .tomItInventoryLocationNoStock

 

So far the general code I have (thanks to some help on StackEx) is as follows:

 

$(document).ready(function(){

if (document.getElementsByClassName(".tomItInventoryLocationNoStock") != null){

var element = document.getElementsByClassName(".btn.btn--full.add-to-cart");

element[0].setAttribute("disabled", "");

}

});

 

 

In a JSFiddle this works great with a straight forward HTML span and button with those classes. Here's where the Shopify-specific question comes in. We already have some JS in our theme to handle deactivating the add to cart button as well as changing the text to our soldOut string:

 

$(selectors.addToCart, this.$container).addClass(classes.disabled).prop('disabled', true);

$(selectors.addToCartText, this.$container).html(theme.strings.soldOut);

 

 

Could I simply replace the section from my initial code with those two lines so it looks like this? I've tried putting the following in my theme and while the console spits out no errors, the button doesn't change either. Any help would be much appreciated!

 

$(document).ready(function(){

if (document.getElementsByClassName(".tomItInventoryLocationNoStock") != null){

var element = document.getElementsByClassName(".btn.btn--full.add-to-cart");

$(selectors.addToCart, this.$container).addClass(classes.disabled).prop('disabled', true);

$(selectors.addToCartText, this.$container).html(theme.strings.soldOut);

}

});

 

0 Likes