0
votes

I am adding swatches to my shopify site via this tutorial and I think they are great, but I was hoping to have them be a bit "smarter".

http://docs.shopify.com/manual/configuration/store-customization/add-color-swatches-to-your-products#Demo

If I have a hat with 4 variants -- sm/red, md/red, sm/blue, md/blue -- 4 buttons show up on the product page. 2 on top, 1 that says "sm" and 1 that says "md" Below those 2 buttons are 2 buttons for the color, 1 that is red and 1 that is blue.

Lets say I have everything in stock except for sm/red. The customer clicks the button "sm" and then sees that there are two color options below it. Unfortunately, they click red, and find out it is sold out by "add to cart" button changing to say "sold out".

I would PREFER if the user clicked the "sm" button, that the red swatch greyed out or got an X, so that the user immediately received feedback on availability.

How hard would it be to make this happen?

1

1 Answers

3
votes

That's not too difficult at all. If you have already implemented the colour swatches as per the Shopify tutorial you mentioned in your question, then you just need to add some extra code to the selectCallback function.

Add to product.liquid:

...

var selectCallback = function(variant, selector) {

  ...

  var selectedSize = jQuery('.size.options li.selected span').text();

  if (selectedSize.length > 0) {
    var variants = selector.product.variants;
    var variantTitles = [];
    var i;

    for (i = 0; i < variants.length; i++) {
      variantTitles.push(variants[i].title);
    }

    jQuery('.color.options li').each( function() {
      var variantTitle = selectedSize + " / " + jQuery('div', this).text();

      // if variantTitle is a valid variant & not sold out, remove unavailable class
      var variantIndex = jQuery.inArray(variantTitle, variantTitles);
      if (variantIndex != -1 && variants[variantIndex].available == true) {
        jQuery('span', this).removeClass('unavailable');
      }
      // if not a valid variant or sold out, add unavailable class
      else {
        jQuery('span', this).addClass('unavailable');
      }
    });
  }
};

...

Add to swatches.liquid (within the <style> tag):

.unavailable { opacity: 0.2; }

Then if you have 2 sizes (SM, MD) and 2 colours (Red, Blue), and "SM / Red" is sold out, you get this:

Small/Red sold out

I've also put this code in a gist.