How to Layer image on top of another to show different variant of a product?

36 Views Asked by At

I'm working on an e-commerce web site. It has few products with multiple color variants. Each product has 3 options that can each have 3 different colours. For example:

Product 1 -> Option 2 -> Red

or

Product 1 -> Option 1 -> Black

Upon selecting the colour choice the product image needs to change to this colour to reflect the change.

Obviously, this could be achieved using multiple images. The only problem I have here is the sheer amount of images I would have to create, one for each possible combination.

I would prefer something which would simply layer the option on top of a base image.

Any ideas on updating colour options on an image without creating individual images for each option?

1

There are 1 best solutions below

3
cssyphus On

Something like this might give you a place to start:

const $ = document.querySelector.bind(document);

$('.row').addEventListener('mouseover', hdl_mousein);

function hdl_mousein(e){
  if (e.target.classList.contains('btn') ){
    const col = e.target.getAttribute('data-color');
    const img = e.target.closest('.card').querySelector('img');
    if (col == 'red'){
      img.classList.remove('imgGreen');
      img.classList.add('imgRed');
    } else {
      img.classList.remove('imgRed');
      img.classList.add('imgGreen');
    }
  }
}
.row {display:flex;}

.card{padding:20px 40px;margin-right:20px;}

.btnRow{display:flex;}
.btn {padding:10px 20px;margin-right:10px;border:1px solid grey;border-radius:4px;cursor:pointer;}

.imgRed{filter: grayscale(100%) sepia(100%) hue-rotate(240deg);}
.imgGreen{filter: grayscale(100%) sepia(100%) hue-rotate(90deg);}
<div class="row">


  <div class="card">
    <div class="imgBland"><img src="https://picsum.photos/200/100" /></div>
    <div class="btnRow">
      <div class="btn" data-color="red">Red</div>
      <div class="btn" data-color="green">Green</div>
    </div>
  </div><!-- .card -->

  <div class="card">
    <div class="imgBland"><img src="https://picsum.photos/220/100" /></div>
    <div class="btnRow">
      <div class="btn" data-color="red">Red</div>
      <div class="btn" data-color="green">Green</div>
    </div>
  </div><!-- .card -->


</div><!-- .row -->

Reference:

css filter to make elements one color