- Keeps href for right-click/new-tab; intercepts only normal left-clicks
*/
(function(){
// helper: extract URL from CSS background-image value like: url("...") or url(...)
function extractUrlFromCss(bg){
if(!bg) return null;
var m = bg.match(/url\((['"]?)(.*?)\1\)/);
return m ? m[2] : null;
}
// click handler (delegated)
document.addEventListener('click', function(e){
// Find nearest element that looks like a swatch. Adjust selector if your theme uses different class.
var swatch = e.target.closest('.color-swatch, .js-collection-swatch, .swatch, .swatch__item');
if(!swatch) return;
// If user used modifier keys (ctrl/cmd/shift/alt) or middle-click, allow default behaviour (open in new tab/window)
if (e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) {
return; // do not intercept
}
// Only intercept anchors or elements that have href-like behaviour; if it's a plain span and you still want intercept, remove this guard.
var href = swatch.getAttribute && swatch.getAttribute('href');
// prevent navigation for normal left-clicks
e.preventDefault();
// Try to get the image URL from data attribute first (recommended)
var imgUrl = swatch.dataset && (swatch.dataset.imageUrl || swatch.dataset.image || swatch.dataset.imageUrl900 || swatch.dataset.imageUrl600);
// fallback: if the swatch uses inline style background-image
if(!imgUrl){
var inlineBg = swatch.style && swatch.style.backgroundImage;
imgUrl = extractUrlFromCss(inlineBg);
}
// fallback: computed background-image (if background-image set in CSS class)
if(!imgUrl){
try {
var cs = getComputedStyle(swatch);
imgUrl = extractUrlFromCss(cs.backgroundImage);
} catch(err) { /* ignore */ }
}
// fallback: try to infer product card from nearest ancestor
// Prefer a wrapper that has data-product-id, otherwise use closest grid item
var productCard = swatch.closest('[data-product-id]') || swatch.closest('.grid__item, .grid-product, .product-card, .product-item');
if(!productCard){
// If we can't find a card, try to locate one by walking up to a parent section then finding the first grid item
var section = swatch.closest('section, .collection, .grid');
if(section) productCard = section.querySelector('.grid__item, .grid-product, .product-card, .product-item');
}
if(!productCard){
// Nothing we can update — early exit (link was kept so user can still open it if needed)
return;
}
// find image element inside the card - be conservative and pick the visible product image
// adjust these selectors if your theme uses a different structure
var imgEl = productCard.querySelector('.grid-product__image-mask img, .product-card__image img, img.product-main-image, img');
if(!imgEl && imgUrl){
// If there's no , maybe the card uses a background-image wrapper
var bgTarget = productCard.querySelec