changing image with buttons | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

changing image with buttons

i'm trying to create a lightbox that change image to the right or to the left depending on which button you click. It kinda work, but the image only change by one, even if there are four image in the array. I think that's because the value of "i" always go back to 1 everytime i click, but i don't know how to solve it. photoContainer.addEventListener('click',(e)=>{ let i = 1; if(e.target.id === 'btn-left' || e.target.id === 'arr-left'){ if(i !== 0){ i -= 1; photoContainer.style.cssText = `background-image: ${imgFolder[i]}; background-position:center; background-size:cover;`; } } if(e.target.id === 'btn-right' || e.target.id === 'arr-right'){ i += 1; photoContainer.style.cssText = `background-image: ${imgFolder[i]}; background-position:center; background-size:cover;`; } })

24th Mar 2020, 4:30 PM
Francesco Paolini
Francesco Paolini - avatar
1 Answer
+ 2
Create global variable i. Set let i = 1 outside the event listener and remove the let i = 1 inside it.
24th Mar 2020, 4:52 PM
Russ
Russ - avatar