+ 1
JS, HTML, How to change image of an <img> onclick of another <img>? loop
I have 3 different images (<img> elements). And another <img> inside a <main>. What I want to do is... When you click on the first image, the image inside the <main> changes to whatever the first image is. Same thing for image 2: when you click on image 2 the image inside the <main> changes to whatever image 2 is. I could just use on click for each of the images clicked, but imagine if I had a thousand images. I want to be able to loop instead. But I don’t know how. Code: https://code.sololearn.com/WXljmiYY5154/?ref=app
6 Antworten
+ 1
you're close.
create a variable to hold an index of which image is shown from the array. like img_now = 0;
on image click, change the image src to images[img_now]; then change value of img_now
event.target.src = images[img_now++]
dont forget to reset it back to 0 if img_now is larger than your array size
+ 1
Taste should I put e.target.src = images[img_now++] inside the foreach (at the bottom, in comments), or where?
Also, where did e. come from? Like is ot a variable, or ..
+ 1
in the click event.
event listener are actually send Event object to callback. you can use them to retrieve the element that trigger the event (in this case is <img>).
let img_now = 0;
elm.addEventListener('click', function(event) {
event.target.src = images[img_now++]
//event.target here is refer to clicked <img>
//that triger the event
})
+ 1
Mirielle👽 yea. is that ES6 ?
0
Taste this is what I got so far:
https://code.sololearn.com/WXljmiYY5154/?ref=app
event.target ... is changing the .src of the clicked element.
instead, it should change the main_bc (the <img> inside the <main>).... based on which image (element) is clicked.
I tried to put event.target.src, it says undefined.