skip to Main Content

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


  1. 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>
    Login or Signup to reply.
  2. 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;

    const mainImage = document.getElementById('mainImage');
    
    mainImage.addEventListener('click', () => {
        const nextSize = parseInt(mainImage.src.split('/')[3]) + 1;
        mainImage.src = `https://dummyimage.com/${nextSize}`;
    })
    

    Image elements can also have the src attribute set with = instead of going through the hassle of setAttribute.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search