Search code examples
javascriptarraysimageonclickcycle

Change and cycle through images onclick in Javascript


I am just trying to cycle through all my images and then do nothing at the end via an onclick function. However I am having trouble. Any suggestions would be great.

<SCRIPT>

var quizImagesB = new Array(); 

 quizImagesB[0]="images/dratiniB.png"
 quizImagesB[1]="images/parasB.png"
 quizImagesB[2]="images/mewB.png"
 quizImagesB[3]="images/doduoB.png"
 quizImagesB[4]="images/meowthB.png"
 quizImagesB[5]="images/cloysterB.png"
 quizImagesB[6]="images/ponytaB.png"
 quizImagesB[7]="images/articunoB.png"
 quizImagesB[8]="images/flareonB.png"

function updateImgB(){
for(var i=0; quizImagesB<.length; i++){
var url = 'url(' + quizImagesB[i] + ')';    //alters css
document.getElementById('pkmnImg').style.backgroundImage=url;
 }
}

</SCRIPT>

<style type="text/css">
#pkmnImg
{
background-image: url(images/charmanderB.png);
background-repeat: no-repeat;
text-align: center;
width: 400px;
height: 450px;
margin-top: 10px;
margin-left: 15px;
}</style>

<FORM>
 <INPUT TYPE="Button" VALUE="Change the image source" onClick="updateImgB();">
</FORM>

<div id ="pkmnImg"></div>

Solution

  • Ok this should work. Instead of looping through the array you want to increase the value of i by 1 on each click, allowing you to cycle through the array this way - see jsfiddle - https://jsfiddle.net/ffd7tmwy/1/

    Javascript:

        var quizImagesB = new Array(); 
    
         quizImagesB[0]="images/dratiniB.png"
         quizImagesB[1]="images/parasB.png"
         quizImagesB[2]="images/mewB.png"
         quizImagesB[3]="images/doduoB.png"
         quizImagesB[4]="images/meowthB.png"
         quizImagesB[5]="images/cloysterB.png"
         quizImagesB[6]="images/ponytaB.png"
         quizImagesB[7]="images/articunoB.png"
         quizImagesB[8]="images/flareonB.png"
    
         var i = 0
         function updateImgB(){
            var i = i + 1;
            var url = 'url(' + quizImagesB[i] + ')';
            document.getElementById('pkmnImg').style.backgroundImage=url;
          }
    

    HTML

    <div id='pkmnImg'></div>
    <form>
        <input type="button" value="Change the image source" onClick="updateImgB()">
    </form>