What is the best way to add a color swatch image using Javascript?

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!

Answer №1

To ensure correct functionality, consider renaming your images to match the data-val attribute value. For example, instead of Camel-Beige.png, rename it to Camel Beige.png.

Additionally, update your javascript code accordingly as shown below:

$(function() {
    if($(".new-variant-swatchs").length) {
        $(".new-variant-swatchs").each(function(i) {
            var $thisSelect = $(this);
            var $currentOption = $thisSelect.data('val');
            $thisSelect.find("li").each(function() {
                var $this = $(this);
                var $liText = $this.text();
                var $liVal = $this.data('val');
                $this.css('background', 'url(/assets/'+$liVal+'.png) no-repeat');       
            });
        });
    }
});

Make sure to adjust the asset relative path accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to pass an Array to the Controller

let formData = new FormData(); payloadData = JSON.stringify(payload.unitDoctors); for (var prop in payloadData) { formData.append(prop, payloadData[prop]); } axios({ method: "put", url: apiUrl + payload.id, data: formData }) .then(resp ...

Tips on formatting text as bold or italic when tweeting from my website to our Twitter account

Currently, I am utilizing the Twitter OAuth library in conjunction with PHP to publish a tweet from my website directly to my Twitter account. My main objective is to highlight some text while posting, however, I have not been successful in identifying t ...

Assistance with designing in JavaScript and Python

Currently, I have a setup where my external website is extracting data from an iframe within our internal company intranet using Javascript. The extraction process is successful, but now I am faced with the challenge of accessing this harvested data in ord ...

Dynamically inserting templates into directives

I've been attempting to dynamically add a template within my Angular directive. Following the guidance in this answer, I utilized the link function to compile the variable into an HTML element. However, despite my efforts, I haven't been success ...

Angular Pagination: Present a collection of pages formatted to the size of A4 paper

Currently, I am working on implementing pagination using NgbdPaginationBasic in my app.module.ts file. import { NgbdPaginationBasic } from './pagination-basic'; My goal is to create a series of A4 size pages with a visible Header and Footer onl ...

Hover over the text below to see an image appear in its place

I'm looking to swap out some text with an image when hovering over it, using basic HTML/CSS. NO: show the image below the text NO: display the text on top of the image NO: replace one image with another YES: replace the text with an image ...

Issue with calculating positions in the jquery.quicksand plugin

I've been playing around with a website for the past couple of days and I have successfully implemented the jquery.quicksand plugin to organize my portfolio entries. However, I've run into an issue when selecting the 'all' filter. If a ...

What is the process of transforming a String into a Function prototype in JavaScript?

Recently, I encountered a JavaScript object containing key-value pairs with functions as values: var serial = { open: function(a, b) { // do something.. }, close: function (a,b) { // do something } } Due to certain requirements, I had ...

Step-by-step guide on how to prioritize rendering the login page before the ngView in AngularJS in order to

As I begin my journey with Angular JS, I am eager to implement security measures in my application. My intention is to set up a log-in page as the default landing page for my single page application. Can anyone provide guidance or recommendations on how ...

Is there a way to convert my function into a variable in order to execute an array of statements

I'm struggling to convert this code into a variable. I need to bind it inside a statement execute array. This is the code I am working on, which retrieves the current date and timezone. I attempted using $date = function() {}, echo $date(); but that ...

Combining Java for the back-end and JavaScript for the front-end: a comprehensive guide

Looking for advice on integrating a Java back-end with a JavaScript, HTML 5 front-end in my web application. Any tips on passing content between the two languages? ...

I'm facing an issue with my 'root' div on ReactJS - it doesn't stretch all the way to the top. Any suggestions on how I can make it expand properly

While I realize this issue has been discussed extensively, none of the suggested solutions have worked for me. As a final attempt to resolve it, I am turning to you all here. The point at which my root div stops is puzzling: I've explicitly defined ...

The site cache appears to be deactivated, but the source of the deactivation remains unclear. Can you help identify the issue?

On my PHP website, the <head> tag in the HTML includes: <meta http-equiv="Cache-Control" content="max-age=300"/> However, when checking the headers, it shows: Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre- ch ...

What are the steps for implementing videojs vr in a Vue.js project?

After installing the videojs vr with npm install --save videojs-vr, I attempted to use it in my project: https://i.stack.imgur.com/lSOqF.png However, I encountered this error message: https://i.stack.imgur.com/QSe1g.png Any assistance would be greatly ...

Is it possible for me to adjust these two images to fit the screen perfectly?

Technologies: CSS React JPG/PNG Objective: I am striving to resize two images to achieve this desired look: https://i.stack.imgur.com/B1b0h.png I am currently developing a 'skirt customizer' for either my mom or portfolio, where users can m ...

Use JavaScript to gather various data forms and convert them into JSON format before transmitting them to PHP through AJAX

My understanding of JSON might be a bit off because I haven't come across many resources that discuss posting form data via JSON/AJAX to PHP. I often see jQuery being used in examples, but I have yet to delve into it as I've been advised to firs ...

Error: Module 'config' not found by Jest

I have encountered an issue while using Jest to test my api calls file. When running a simple test, I received an error Cannot find module 'config' from 'api.service.js'. This error is related to the import statement at the top of my ap ...

Troubleshooting the integration of Text Mask Library with Vue - issue: no export named 'default' available

I was able to implement the vanilla JavaScript version: var maskedInputController = vanillaTextMask.maskInput({ inputElement: document.querySelector('.myInput'), mask: [/\d/, /\d/, '/', /\d/, /\d/, '/ ...

I desire my grid to exhibit an identical appearance to that of the jquery datepicker

I have an interactive element called the "open grid" that, when clicked on, reveals a grid of buttons. I'm looking for help with coding it so that instead of being displayed below the textbox, the grid of buttons can be hovered over the "open grid" li ...

Struggling to retrieve data from the HTML Dom? I have already tried using getAttribute() and getText() methods within Selenium WebDriver

I attempted to extract text/value from the Html Dom using getAttribute() and getText() methods in WebDriver, but I wasn't able to retrieve any values in the console. Could someone please assist me in resolving this issue? The image provided does not c ...