skip to Main Content

In WordPress and Woocommerce, I am attempting to apply javascript within the child theme functions.php, so if a user clicks a specific product attribute color swatch, it will change a preview image (shown below the swatch selectors) with a specific ID to a new image source URL. I have very limited javascript knowledge and am fumbling my way through this.

I was able to get one single swatch (Black) to change the target image, but I cannot figure out how to repeat the command for the other swatches. Here is what I have so far:

add_action( 'woocommerce_before_single_product', 'bluetera_swatch_onclick' );


function bluetera_swatch_onclick() { ?>


    <script type='text/javascript'>
        var input = document.getElementById("ecorigidswatches_Black");
        input.onclick = function swapproductimg() {
        document.getElementById('selected-swatch').src="https://www.laserfelt.com/wp-content/uploads/2021/06/BlackHexagon.jpg";

}

    </script>
    <?php
}

Here is a link to the product page in question:

https://www.laserfelt.com/product/hexagon-acoustic-wall-tiles/

I was also trying to create a conditional statement that would only execute this function if the user was viewing a product in a specific category. But I would not figure out how to do that either. All of my attempts failed. We have different sets of color swatches and I am trying to figure out a way to have the script load only when it is needed.

I am also wondering if this would be the most efficient way to achieve the desired result, or if there is a better way that would improve page load speeds? I am limited to working with the existing plugin that creates these product swatch options. That is why I am having to insert the onclick function in a roundabout way.

We do not want to use any of the pre-existing swatch plugins that only changed the main product image.

I would really appreciate some pointers, tips and direction. Thanks!

— UPDATE —

Based on a tweak of Michal’s recommendation, I also tried this, but it did not work:

var black = document.getElementById("ecorigidswatches_Black");
var berry = document.getElementById("ecorigidswatches_Berry");
if (berry.checked = true) {
  document.getElementById('selected-swatch').src="https://www.laserfelt.com/wp-content/uploads/2021/06/BerryHexagon.jpg";
} elseif (black.checked = true) {
  document.getElementById('selected-swatch').src="https://www.laserfelt.com/wp-content/uploads/2021/06/BlackHexagon.jpg";
}

— UPDATE – PARTIAL SOLUTION —

With the help of Vladimir, I was able to get this to work, but if I click on any other product attribute or input, it changes the target img src to "undefined" and the image becomes broken. Here was my working code that is in functions.php file:

add_action( 'woocommerce_before_single_product', 'bluetera_swatch_onclick' );


function bluetera_swatch_onclick() { ?>


    <script type='text/javascript'>
        
        
  
  const images = {
    'ecorigidswatches_Berry':"https://www.laserfelt.com/wp-content/uploads/2021/06/BerryHexagon.jpg",
    'ecorigidswatches_Black':"https://www.laserfelt.com/wp-content/uploads/2021/06/BlackHexagon.jpg", 
    'ecorigidswatches_Brown':"https://www.laserfelt.com/wp-content/uploads/2021/06/BrownHexagon.jpg"
  };
  
  //select all elements with data-color attribute
  const swatch = document.querySelectorAll('[id]'); 

  swatch.forEach(element => {
    element.addEventListener('click', () => {
      let color = element.getAttribute('id');
      document.getElementById("selected-swatch").src = images[color];
    });
  });
  

    </script>
    <?php
}

2

Answers


  1. var black = document.getElementById("ecorigidswatches_Black");
    if (black.checked = true) {
      document.getElementById('selected-swatch').src="https://www.laserfelt.com/wp-content/uploads/2021/06/BlackHexagon.jpg";
    } elseif (condition2) {
      document.getElementById('selected-swatch').src="https://www.laserfelt.com/wp-content/uploads/2021/06/color.jpg";
    }
    
    Login or Signup to reply.
  2. To loop the image source using an array with JavaScript:

    1. Create an array that contains your image sources:
    2. Whenever the user clicks the image, the changeImage() function will be called, which updates the src attribute to point to the next image in the array
      const images = [
        "https://placeimg.com/170/170/nature",
        "https://placeimg.com/170/170/people", 
        "https://placeimg.com/170/170/tech"
      ];
      let currentIndex = 0;  // Keep track of which image is currently displayed
    
      function changeImage() {
        document.getElementById("myImage").src = images[currentIndex];
        currentIndex = (currentIndex + 1) % images.length;  // Move on to next image
      }
    
      // Call the changeImage function whenever the user clicks the image
      document.getElementById("myImage").addEventListener("click", changeImage);
    <img id="myImage" src="https://placeimg.com/170/170/any">

    Edit:
    Creates an object images with properties red, blue and green. It selects all elements with a data-color attribute and attaches a click event listener. On click, it retrieves color value from the data-color attribute and updates the image source.

      const images = {
        'red':"https://placehold.co/250x250/red/red/png",
        'blue':"https://placehold.co/250x250/blue/blue/png", 
        'green':"https://placehold.co/250x250/green/green/png"
      };
      
      //select all elements with data-color attribute
      const swatch = document.querySelectorAll('[data-color]'); 
    
      swatch.forEach(element => {
        element.addEventListener('click', () => {
          let color = element.getAttribute('data-color');
          document.getElementById("myImage").src = images[color];
        });
      });
      
    <img id="myImage" src="https://placehold.co/250x250/lightgray/lightgray/png">
    
    
    <ul>
      <li><button data-color="red">Red</button></li>
      <li><button data-color="blue">Blue</button></li>
      <li><button data-color="green">Green</button></li>
    </ul>

    Extra:

      ul {
        display: flex;
        list-style-type: none; 
        padding: 0;
      }
      
      li {
        margin-right: 10px; /* Add some space between items */
      }
      
      button {
        width: 50px;
        height: 50px;
        border-radius: 50px;
        background: none;
        border: none;
        margin: 0;
        padding: 0;
        font-family: inherit;
        font-size: inherit;
        cursor: pointer;
        outline: none;
      }
      
      [data-color=red] {
        background-color: red;
      }
      [data-color=blue] {
        background-color: blue;
      }
      [data-color=green] {
        background-color: green;
      }
      
      .sr-only {
        position: absolute;
        left: -10000px;
        width: 1px;
        height: 1px;
        top: auto;
        overflow: hidden;
      }
    <ul>
      <li>
        <button data-color="red">
          <span class="sr-only">Red Jacket</span>
        </button>
      </li>
      <li>
        <button data-color="blue">
          <span class="sr-only">Blue Jacket</span>
        </button>
      </li>
      <li>
        <button data-color="green">
          <span class="sr-only">Green Jacket</span>
        </button>
      </li>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search