Shopify Color Swatches
A color variant picker.
About this module
A color-swatch variant picker that selects a product variant and updates the add-to-cart form's variant ID.
Source code
Installation
- 1
Open Shopify Admin
Go to Online Store → Themes.
- 2
Edit code
Click the ellipsis (⋯) next to your theme and choose Edit Code.
- 3
Create the section
In the Sections folder, click Add a new section, name it mh-color-swatches, and replace the contents with the Liquid source below.
- 4
Save
Save the file. The section now appears in the Theme Customizer.
- 5
Add it to the page
Open the Theme Customizer, click Add section, search for it and add it where you like.
Usage
- 1
Paste the section
Create `mh-color-swatches` under Sections and paste the source.
{{ 'styles.css' | asset_url | stylesheet_tag }} {% assign option_index = 0 %} {% for option in product.options %} {% if option == section.settings.option_name %}{% assign option_index = forloop.index0 %}{% endif %} {% endfor %} <div class="mh-swatches" data-option-index="{{ option_index }}" data-form-selector="{{ section.settings.form_selector }}"> <span class="mh-swatches-label">{{ section.settings.option_name }}</span> <div class="mh-swatches-options"> {% for value in product.options_with_values[option_index].values %} {% assign variant = product.variants | where: "option" | first %} <button type="button" class="mh-swatch" data-value="{{ value | escape }}" data-color="{{ value | handle }}" aria-label="{{ value }}" ></button> {% endfor %} </div> </div> <script> (function () { var wrap = document.querySelector('.mh-swatches'); if (!wrap) return; var optionIndex = Number(wrap.dataset.optionIndex); var form = document.querySelector(wrap.dataset.formSelector || 'form[action="/cart/add"]'); var select = form && form.querySelector('select[name="id"]'); wrap.querySelectorAll('.mh-swatch').forEach(function (btn) { btn.addEventListener('click', function () { wrap.querySelectorAll('.mh-swatch').forEach(function (b) { b.classList.remove('active'); }); btn.classList.add('active'); var value = btn.dataset.value; if (select) { Array.from(select.options).forEach(function (opt) { var text = (opt.textContent || '').trim(); if (text.indexOf(value) !== -1) { select.value = opt.value; select.dispatchEvent(new Event('change')); } }); } }); }); var first = wrap.querySelector('.mh-swatch'); if (first) first.classList.add('active'); })(); </script> {% schema %} { "name": "MH Color Swatches", "tag": "div", "settings": [ { "type": "text", "id": "option_name", "label": "Option name", "default": "Color" }, { "type": "text", "id": "form_selector", "label": "Add to cart form selector", "default": "form[action="/cart/add"]" } ], "presets": [{ "name": "MH Color Swatches", "category": "ModuleHarbor" }] } {% endschema %} - 2
Configure in the customizer
Adjust the settings that ship with the section schema.