0

How can I have it so that each time the button is clicked the array is iterated through once? If I click it a second time, it should display the second array element, etc. until it iterates through the entire array.

JavaScript:

var images = [
    "<img src='first.png' />",
    "<img src='second.png' />",
    "<img src='third.png' />",
    "<img src='kitten.png' />"
];

var button = document.getElementsByClassName("btn-lg")[0];

button.addEventListener("click", function(){
    for(i = 0; i < 5; i++) {    
        jQuery('.row.text-center').append(images[i]);
    }       
});

HTML:

<div class="row text-center">
    <button type="submit" class="btn btn-lg btn-info">Click Here!</button>
</div>

jsfiddle: http://jsfiddle.net/KVs6S/1/

Thanks!

Anon
  • 94
  • 2
  • 10

4 Answers4

2

Since you are using jQuery then you may try (don't mix up vanilla js liike addEventListener)

$(function(){
    var images = [
        "http://imageshack.us/a/img9/6564/3qv9.png",
        "http://imageshack.us/a/img9/4521/3dmc.png",
        "http://imageshack.us/a/img28/3608/1x6h.png",
        "http://imageshack.us/a/img850/1713/5i6g.png"
    ];

    $(".btn-lg").on("click", function(){
        if(images.length) {
            var img = $('<img/>', { 'src':images.pop() });
            $('.row.text-center').append(img);
        }
    });
});

Also, Array.pop() is enough for this and just keep the urls instead of images in the array.

DEMO. (Images are getting appended but for your big button these are not visible.)

The Alpha
  • 143,660
  • 29
  • 287
  • 307
1

Externalize the counter :

var i=0, images = [
    "<img src='first.png' />",
    "<img src='second.png' />",
    "<img src='third.png' />",
    "<img src='kitten.png' />"
];

jQuery('.btn-lg').on("click", function(){
     if (i>=images.length) return;
     jQuery('.row.text-center').append(images[i++]);
});
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

Make i a variable starting from 0 and increment it resp. when lenght is greather than images count - restart:

var i = 0;
var button = document.getElementsByClassName("btn-lg")[0];

button.addEventListener("click", function(){
    if (i == 4) { i = 0; /* OR return; to stop */ }
        jQuery('.row.text-center').append(images[i++]);

});
keenthinker
  • 7,645
  • 2
  • 35
  • 45
1

Use a closure:

function yield(lenArray)  {
  var i=0;
  console.log("outer",lenArray);
  return function()  {
  if (i<lenArray) {
    console.log("inner",i);
    jQuery('.row.text-center').append(images[i++]); 
    }
  }
}

button.addEventListener("click", yield(5));

How do JavaScript closures work?

Community
  • 1
  • 1
vinaut
  • 2,416
  • 15
  • 13