'How I do change the BIG image to the thumbnail images when I click the Color Swatches on the right?
How I do change the BIG image to the thumbnail images when I click the Color Swatches on the right? I guess I need to map the thumbnail images to the color swatches? Im hoping to loop through the thumbnail images when i click through the color swatches. so when you click the first color swatch, the BIG image will update to show the FIRST thumbnail and so forth
let colorSwatch = document.querySelectorAll(".color-swatches");
let smallImg = document.getElementsByClassName("sec");
for(let i= 0; i <colorSwatch.length; i++){
colorSwatch[i].addEventListener("click", changeColor);
}
function changeColor(){
for (let a = 0; a < smallImg.length; a++){
document.querySelector(".main-image").setAttribute("src",smallImg[a].getAttribute("src"));
console.log(a);
}
}
<div class="image-container">
<img
src="https://source.unsplash.com/400x400/?stationery"
class="item main-image"
/>
<div class="secondary-image">
<img
src="https://source.unsplash.com/100x100/?pen"
class="item sec item-1 active "
/>
<img
src="https://source.unsplash.com/100x100/?pencil"
class="item sec item-2"
/>
<img
src="https://source.unsplash.com/100x100/?notepad"
class="item sec item-3"
/>
<img
src="https://source.unsplash.com/100x100/?eraser"
class="item sec item-4"
/>
</div>
</div>
<div class="product-info">
<h1>Product Name</h1>
<p>Product description goes here two line product description</p>
<h3>Color</h3>
<div class="color-swatches">
<img src="color-swatch.svg" class="swatch color-1" />
<img src="color-swatch.svg" class="swatch color-2" />
<img src="color-swatch.svg" class="swatch color-3" />
<img src="color-swatch.svg" class="swatch color-4" />
</div>
<h3>Quantity</h3>
<div class="quantity">
<!-- <svg>
<ellipse cx="35" cy="35" rx="35" ry="35" />
</svg> -->
<img
src="https://cdn.glitch.global/935c1b3a-2d6f-42b5-aab8-2ea9c89cca70/minus-circle.svg?v=1645435804825"
id="minus-icon"
/>
<h3 id="quantity-value">1</h3>
<img
src="https://cdn.glitch.global/935c1b3a-2d6f-42b5-aab8-2ea9c89cca70/plus-circle.svg?v=1645435811670"
id="plus-icon"
/>
</div>
<button class="btn-primary add-to-cart-btn">Add to Cart</button>
</div>
Solution 1:[1]
Look at this line: document.querySelector(".main-image").setAttribute("src",smallImg[a].getAttribute("src")); ...you select the source of your image that has sec as class, this means you get this source: src="https://source.unsplash.com/100x100/?eraser".
So that's the problem, the 100x100.
As a workaround you can use this CSS style:
img.item.main-image {
width: 300px;
height: 300px;
}
...and change the source of your thumbnails like this:
https://source.unsplash.com/300x300/?eraser
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | NineCattoRules |
