Search code examples
javascriptevent-listenerdom-manipulation

how can i change the image inside the image tag ( with a class of innerMainImg) how do i pass on to the next image when i click on the current image?


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);
    };
}

Solution

  • 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:

    const img = document.querySelector("#mainImg .innerMainImg");
    const imgNext = () => {
      let imgNumber = ((img.dataset.index || 0) % 4);
      const actualImage = "images/prot" + ++imgNumber + ".jpg";
      img.setAttribute("src", actualImage);
      img.setAttribute('alt', imgNumber); // just for this demo, can be removed.
      img.dataset.index = imgNumber;
    } 
    img.addEventListener('click', imgNext);
    img {
      width: 100px;
      height: 100px;
      border: 1px solid #CCC;
      display: block;
    }
    <div id="mainImg">
      <img class="innerMainImg" />
    </div>