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

Storing various data in separate tables using MySQL and Node.js

Currently, I am working with three tables - user, modules, and an intermediate table called user_module. To perform an inner join between the user and module tables, I need to access the user_module table. "SELECT user.uName, module.moduleName FROM user_m ...

Switch up the styling of a component by updating its properties with a switch statement

Although there is a similar question, my query has a unique requirement. I have defined the common styles for my button and implemented a function using a switch statement with different properties for various buttons across different pages. However, for ...

The menu will showcase all currently active sub-category items whenever an item below is selected (using Joomla/Mosets Tree)

I am currently managing a Joomla website that utilizes Mosets Tree for a business directory. One issue I have noticed is that on the right side of the site, all the categories are listed. When you expand sub-categories and then roll over to another menu it ...

creating a while loop in node.js

In C#, the following code would be used: double progress = 0; while (progress < 100) { var result = await PerformAsync(); progress = result.Progress; await Task.Delay(); } This concise piece of code spans just 7 lines. Now, how can we ...

The collapsible list feature that includes the use of plus and minus signs is malfunctioning

Below is the script that I wrote to address this issue, but for some reason the + and - swapping is not functioning correctly. $('.showCheckbox').click(function(e) { var dynamicBox = $(this).attr('val'); var collapseSign = $(th ...

Using either Canvas.toBlob or Canvas.toDataURL results in me obtaining an image with a transparent

Hey there! I'm currently working on a project that requires the user to crop and upload images. For cropping, I am utilizing react-cropper. My challenge lies in dealing with Chrome's limitation on dataURL to 65529 pixels as mentioned in this M ...

Building a Mongoose Schema with an Array of Object IDs: A Step-by-Step Guide

I created a user schema using mongoose: var userSchema = mongoose.Schema({ email: { type: String, required: true, unique: true}, password: { type: String, required: true}, name: { first: { type: String, required: true, trim ...

The hyperlink element is failing to load in a particular frame

I've been attempting to load the URL of an anchor tag in a specific frame. I've tried various methods through online searches, but have not found a satisfactory solution. Can someone please assist me with how to load the href URL in a particular ...

Passport is implementing multistrategies for multiple authentications simultaneously

After configuring Passport.js to utilize multiple strategies, I encountered an issue: passport.authenticate(['bearer', 'facebook-token', 'google-token', 'linkedin-token'],function(err, user, info) ... Although it i ...

The CSS box-shadow property failed to render properly on Internet Explorer and Safari browsers

#keyboard { position: fixed; background: #eee; display: none; border: 1px solid #ccc; border-radius:7px; width: 950px; height: 300px; padding: 5px; cursor: move; background-image:url('BackgroundImage.jpg'); box-shadow: -5px -5px 5px 5px #888; -m ...

How to send emails in the background using a React Native app

I'm looking to incorporate email functionality into a React Native app so that it can send messages automatically when certain actions occur in the background. ...

Is it possible to modify the inline onkeyup function?

Looking for a solution to change the onkeyup function in a textarea element from 255 characters to 150 characters without directly editing the code? <textarea cols="50" rows="4" id="textbox" onkeyup="limitArea(this, 255, '')"></textarea ...

Perform a series of tasks concurrently within a function using Grunt

I am currently utilizing grunt-shell along with other custom tasks in my project. In one of my tasks, I need to execute these tasks sequentially and verify the output of each task. Here is a simplified representation: grunt.task.registerTask('test&ap ...

How to center a text box within a div using CSS

Looking for equal margins on top and bottom? Here's how to achieve it: If you have a container div like this: <div id="search"> <input id="txtSearch" type="txt"> </div> Your CSS should look something like this: #search{ m ...

The conclusion of jQuery's nested animation

Functioning, But Page Transitions Inconsistent What I Believe to be the Correct Approach, But Event Triggering Issue Currently, I am experimenting with page transitions and utilizing bind() to detect the end of the CSS event transition. When a class is ad ...

Discover the depth of a deeply nested array

I have a complex array structure that looks something like this: I am trying to determine the depth of this nested array, focusing on the element with the most deeply embedded children. let arr = [ { name: 'tiger', children: [{ ...

Navigating to a different page by clicking on a Table Row in react-table

Whenever I click on a table row, I am unable to navigate to another page. Although I have successfully implemented the getTdProps function to retrieve properties from the table row upon clicking on it, I'm facing difficulty in using 'react-route ...

Unable to reset disabled styling for CSS select box

My Windows 8 app consists of two pages: Page1.html and Page2.html. Page1 references ui-light.css and page1.css, while Page2 references ui-light.css and page2.css. In the ui-light.css file, there is a rule defined for the disabled state of select boxes. I ...

Finding the element and extracting its text value

Below is the HTML code: <span> <b>Order number:</b> </span> <span>A36HASJH</span> The value within the span element, A36HASJH, is dynamic and changes with each order. How can I identify this element and store it as a s ...

What is causing the ng-show function to malfunction after building with phonegap?

My current javascript framework for my PhoneGap app is the Ionic Framework. I have a specific item on one of my pages that I want to make expandable and collapsible by clicking an anchor on the page. Here is what the code looks like: In the HTML file: & ...