i am creating a webpage page in which i have a div containig an image the img tag has a class of innerMainImg. i have four images in an "images" folder within my project. the images are "prot1, prot2, prot and prot4". i tried to ad a click event listener to my innerMainImg so that when i click on the first image (prot1.jpg), the image then changes to prot2 and when i click again, it prot2.jpg changes to prot3.jpg and so on. but my code is not really working. how can i fix that ?
var imgNumber = 1;
for(i = 1; i < 5; i++){
imgNumber = i;
var actualImage = "images/prot" + imgNumber + ".jpg";
document.querySelector("#mainImg .innerMainImg").addEventListener("click", imgNext);
function imgNext(){
document.querySelector("#mainImg .innerMainImg").setAttribute("src", actualImage);
};
}
2
Answers
The approach you’re using – looping to create multiple event handlers isn’t quite right. A better approach would be to create a single event handler and then increment the index value of the image within that, something like this:
Since you’re using a single element to display the image there’s no need for it to be in a loop, let alone adding the event listener / defining a function multiple times within it. This will lead to severe unintended side-effects.
An element only needs to have the event listener added once, and the callback function used defined only once (or written within the call to addEventListener itself).
Take the following as an example: https://jsfiddle.net/qtr8aL0b/
The JS part of it specifically, this will update the
src
on every click;Image elements can also have the
src
attribute set with=
instead of going through the hassle ofsetAttribute
.