Skip to content
Advertisement

i want to change image using for loop in js without using jQuery

i don’t understand why this is not working? plz tell me what i missed in this code ** html **

<div id="img">
            <img class="images"src="images/boy1.jpg">
        </div>

** js **

var images = new Array();

images[0] = "/images/boy1.jpg";
images[1] = "/images/boy2.jpg";
images[2] = "/images/boy3.jpg";
images[3] = "/images/girl1.jpg";
images[4] = "/images/girl2.jpg";


function changeImg(){

    let img = document.querySelector(".images");   
    for(let i=0;i<images.length;i++){
       img.src = images[i]
    }
}

document.getElementById("btn").addEventListener("click",changeImg)

Advertisement

Answer

Is this what you wish to achieve?

var images = new Array();
var imgIndex = 0;

images[0] = "/images/boy1.jpg";
images[1] = "/images/boy2.jpg";
images[2] = "/images/boy3.jpg";
images[3] = "/images/girl1.jpg";
images[4] = "/images/girl2.jpg";


function changeImg() {
  var myImg = document.getElementById("myImg");
  if (imgIndex < images.length - 1) {
    imgIndex++;
  } else {
    imgIndex = 0;
  }

  myImg.src = images[imgIndex];
}

document.getElementById("btn").addEventListener("click", changeImg);
<div id="img">
  <img id="myImg" class="images" src="images/boy1.jpg">
</div>

<button id="btn">Next</button>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement