0

I´m doing a landing page and wanted to make the main image change when I click on other images. I´ve tried with this

<div class="thumb"> <ul> <li> <img id="img1" class="smallImg coupe" src="./assets/smallCar1.png" alt="small img"> </li> </ul> <ul> <li> <img id="img2" class="smallImg" src="./assets/smallCar2.png" alt="small img"> </li> </ul> <ul> <li> <img id="img3" class="smallImg" src="./assets/smallCar3.png" alt="small img"> </li> </ul> </div> 
function imageChange() { let picDefault = document.getElementById("img"); if ((picDefault = "img")) { picDefault.src = "./assets/img1.png"; } } picDefault.addEventListener(click, imageChange); 
6
  • 2
    click needs to be in quotes in addEventListener() Commented Feb 9, 2022 at 4:11
  • 2
    picDefault() is local to the function, you can't use it outside Commented Feb 9, 2022 at 4:12
  • if ((picDefault = "img")) will never be true. picDefault is a DOM element, not a string. What are you trying to do there? Commented Feb 9, 2022 at 4:12
  • Hey @Barmar, if ((picDefault = "img")) will always be true as it is an assignment with a "truesy" result :D ... Commented Feb 9, 2022 at 4:16
  • 1
    Anyway, what's the question here? Commented Feb 9, 2022 at 4:17

1 Answer 1

1

Sample code for updating an image by clicking on another image. Use case might be completely different.

const thumps = document.getElementsByClassName("thump"); // secondary images const main = document.getElementById("main"); for(let i = 0; i < thumps.length; i ++) { const el = thumps[i] el.addEventListener("click", function(e) { // add click handler const elem = e.target; main.src = elem.src; }) }
#main { max-width: 300px; } .thump { width: 100px; margin: 4px; padding: 2px; border: 1px solid #ccc; display: inline-block; }
<div> <h5>Main Image</h5> <img src="https://images.unsplash.com/photo-1644243019151-0bb97ce1af84" id="main"/> </div> <h5>Click Images below thumpnails to update main image</h5> <div class="row"> <img src="https://images.unsplash.com/photo-1644235279538-4cc7cbdca6a8" class="thump"> <img src="https://images.unsplash.com/photo-1643443026948-c17b9bb16758" class="thump"> <img src="https://images.unsplash.com/photo-1644243019151-0bb97ce1af84" class="thump"> </div>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.