// Product Color Variant Selector // Dynamically adds color selection to product pages (function() { 'use strict'; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } function init() { if (!window.location.pathname.includes('/shop/product/')) return; // Wait a bit for page to fully load setTimeout(() => { const productId = window.location.pathname.split('/').pop(); if (productId) { loadVariants(productId); } }, 500); } function loadVariants(productId) { // Try to fetch variants data fetch('/api/shop/product/' + productId + '/variants') .then(res => res.json()) .then(variants => { if (variants && variants.length > 0) { renderVariants(variants); } }) .catch(() => { // Silently fail if API doesn't exist console.log('Variant API not available'); }); } function renderVariants(variants) { const actionsDiv = document.querySelector('.actions'); if (!actionsDiv || document.querySelector('.product-variants')) return; const html = `

Color: Choose a color

${variants.map((v, i) => `
${v.ColorName}
`).join('')}
`; actionsDiv.insertAdjacentHTML('beforebegin', html); document.querySelectorAll('.variant-swatch').forEach((el, i) => { el.onclick = () => { document.getElementById('selectedVariantName').textContent = variants[i].ColorName; document.getElementById('selectedVariantData').value = JSON.stringify(variants[i]); document.querySelectorAll('.variant-swatch div').forEach((d, j) => { d.style.boxShadow = i === j ? '0 0 0 2px ' + variants[i].ColorHex + ', 0 0 8px ' + variants[i].ColorHex : '0 0 0 2px #ddd'; }); }; }); } })();