Published on

Crafting a Seamless Shopify Experience Connecting Thumbnails to Variants

Authors
  • avatar
    Name
    Entaice Braintrust
    Twitter

Crafting a Seamless Shopify Experience: Connecting Thumbnails to Variants

Let's rewind to the day when we first dipped our toes into the Shopify ocean, perhaps more like a puddle, and felt the zing of excitement backed by a healthy dose of confusion. Remember that moment of clarity mixed with chaos? That's where our story begins, like that time we tried a new restaurant and realized halfway through the meal that we had messed up the order but ended up loving the unexpected dish nonetheless. That’s the essence of exploring Shopify’s coding environment.

Today, we'll unravel the enigma of linking those stubborn thumbnails to product variants using Shopify’s Taste theme. Code can be tricky, like trying to fold a fitted sheet—it looks straightforward until you start. But don’t worry; we’ve got this. We’ll also tackle the side quest of auto-selecting the first available variant when switching categories. Let's dive in!

Connecting Thumbnails to Variant Selection

It was a Tuesday morning when we stumbled upon the riddle of linking thumbnails to their respective variants. Picture this: the sunlit room was filled with the ambient hum of a laptop. We were determined—not unlike Indiana Jones pursuing a lost artifact—to make those thumbnails obediently highlight the correct variant.

To set this up, JavaScript will be our trusty fedora. Here’s the plan:

Step 1: Identify the Product and Thumbnails

First, let's dig into our product section. Open your product-template.liquid file, nestled within the precious confines of Sections. We're eyeing the divs that house these thumbnails and the main image display. Make sure each thumbnail is tagged with a data attribute indicating its variant association.

<img src="{{ image.src }}" data-variant-id="{{ variant.id }}" class="thumbnail-img" />

Step 2: Craft the JavaScript Magic

Now, harness JavaScript's mighty power to listen for a delightful click on any thumbnail and switch the variant accordingly. In the same file, script out this little helper:

document.querySelectorAll('.thumbnail-img').forEach(function (thumbnail) {
  thumbnail.addEventListener('click', function (event) {
    var variantId = event.target.dataset.variantId
    ShopifyAnalyticsJS.setActiveVariant(variantId)
    // Make sure the option selectors are updated
    updateVariantSelectors(variantId)
  })
})

function updateVariantSelectors(variantId) {
  document.querySelector(`option[value="${variantId}"]`).selected = true
  document.querySelector('select').dispatchEvent(new Event('change'))
}

Step 3: Test and Refine

Like a puzzler gazing wondrously at the final piece to fit snugly, hit save, refresh your product page, and let the fruits of your labor shine. Those thumbnails will finally listen, selecting the appropriate variant.

Pre-selecting the First Available Variant

The sun was setting as we turned to the second challenge. Our coffee – or was it tea? – still warm, we contemplated the mysterious dance of unavailable options. Click a variant and if the currently selected option isn’t a match, well, we yearn for it to gracefully swing to the first available choice.

Step 1: Modify JavaScript for Variants

Enhance your JS code to include a check when changing variants:

function updateVariantSelectors(variantId) {
  var variant = product.variants.find((v) => v.id == variantId)
  if (variant && !variant.available) {
    variant.options.forEach((option, index) => {
      if (option.available) {
        document.querySelector(`select[name="options[${index}]"] option`).selected = true
        document
          .querySelector(`select[name="options[${index}]"]`)
          .dispatchEvent(new Event('change'))
      }
    })
  }
}

This script serenades the first available option for a variant, ensuring the melody of customer satisfaction plays on.

Step 2: Revel in Inventory Harmony

Refresh, sip your drink, and smile as you witness that symphonic auto-selection. Glitches may appear, don't fret—debugging is just another chapter in our adventure.

Celebrating the Digital Symphony

Remember, we’re in this together, weaving pieces of code with patience and a sprinkle of innovation. As our Shopify storefront becomes more robust, those early moments of bemusement—much like trying to tame an unruly horse—will transform into elegant rides through peaceful meadows of eCommerce glory. Thank you for letting us join you on this digital odyssey, one line of code at a time.