JS increment by one

Hi,

I have a button that calls the function “changePic”, however when I press the button it only increments imgIndex to 1 and stops. I need it to go all the way to imgList.length-1 and then reset to 0, however this is not happening.

I think it might have something to do with the scope of the variables I’m declaring outside of the function, but I’m not sure how exactly to fix it.

Could someone please help me? I am pulling my hair out over this.

<script>
const imgList = Array("Torben.png", "Torben2.jpg", "Torben3.jpeg", "Torben4.jpeg", "Torben5.jpeg", "Torben6.jpeg", "Torben7.jpeg", "Torben8.jpeg", "Torben9.jpeg",);
imgIndex = 0;
function changePic() {
    if (imgIndex == imgList.length - 1){
        imgIndex = 0;
    }

    else {
        imgIndex =+ 1;
    }

    document.getElementById("DogPic").src = imgList[imgIndex];
}
</script>

Thanks in advance :slight_smile:

Yep, there’s a syntax error. Please note that “+=” and “=+” are totally different.

As stated above, this is wrong.

The right side of the statement (+1) becomes 1 and then it gets assigned to the left side (imgIndex).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.