I'm facing a challenge in Shopify where I need to assign corresponding background images to color swatches. Currently, my icons are set up with the correct links for each color, but they are missing their respective images, similar to this example. I have the images stored in an assets folder, and each image is named to match the color variation. How can I use Javascript to pair each image with its matching icon? I've tried using Liquid, but it doesn't work for me since all the HTML is generated through Javascript. Below is a snippet of my HTML:
<ul class="new-variant-swatchs">
<li class="new-variant-swatch js-new-variant-swatch is-active" data-val="Army Green" data-select="js-option-selector-0"></li>
<li class="new-variant-swatch js-new-variant-swatch" data-val="Burgundy" data-select="js-option-selector-0"></li>
<li class="new-variant-swatch js-new-variant-swatch" data-val="Camel Beige" data-select="js-option-selector-0"></li><li class="new-variant-swatch js-new-variant-swatch" data-val="Candy Red" data-select="js-option-selector-0"></li>
<li class="new-variant-swatch js-new-variant-swatch" data-val="Caramel Brown" data-select="js-option-selector-0"></li><li class="new-variant-swatch js-new-variant-swatch" data-val="Charcoal Grey" data-select="js-option-selector-0"></li>
<li class="new-variant-swatch js-new-variant-swatch" data-val="Heather Grey" data-select="js-option-selector-0"></li><li class="new-variant-swatch js-new-variant-swatch" data-val="Ivory White" data-select="js-option-selector-0"></li>
<li class="new-variant-swatch js-new-variant-swatch" data-val="Muted Black" data-select="js-option-selector-0"></li><li class="new-variant-swatch js-new-variant-swatch" data-val="Navy Blue" data-select="js-option-selector-0"></li>
<li class="new-variant-swatch js-new-variant-swatch" data-val="Rose Pink" data-select="js-option-selector-0"></li>
</ul>
I am new to Javascript, and here's what I attempted (which I know is incorrect, just trying to convey the idea). Your help is much appreciated!
$(function() {
if($(".new-variant-swatchs").length) {
$(".new-variant-swatchs").each(function(i) {
var $thisSelect = $(this);
var $currentOption = $thisSelect.val();
$thisSelect.find("li").each(function() {
var $this = $(this);
var $liText = $this.text();
var $liVal = $this.val();
$this.style.backgroundImage = "url({{ $liVal | handle | append: '.' | append: png | asset_url }}"
}
});
}
});
Thank you for your assistance!