1

I'm just working on simple gallery and want to loop an array once each time I click a button and continue upon clicking again.

My code looks like this:

$(document).ready(function(){
  var pack_img = [
    'image1.jpg',
    'image2.jpg',
    'image3.jpg',
    'image4.jpg',
    'image5.jpg'
  ];

  $("#btn").click(function(){
    for(var i=0; i<pack_img.length; i++) {
       alert(pack_img[i]);
       return false;
     }  
  })
});

I've search already about breaking and continue looping, but seems so very complicated for me

Any idea is greatly appreciated. :)

3 Answers 3

4

Try this :

var _index = -1;
$("#btn").click(function(){

    if(_index < pack_img.length){
         _index ++;
    }else{
         _index = 0;
    }
    alert(pack_img[_index ]);
});
Sign up to request clarification or add additional context in comments.

4 Comments

+1 as you don't need to use a for loop to step through an array.
Works great!!! I haven't thought that it will only require me to use if statement to meet my expectations. Thanks :)
Just an FYI: You can replace your if and else statements with _index = (_index + 1) % pack_image.length;
Or _index = _index < pack_img.length ? _index + 1 : 0;
1

you have to keep track of previous array item like this:

var previous = 0;
$("#btn").click(function(){

    for(var i=previous; i<pack_img.length; i++) {
       previous = i;
       alert(pack_img[i]);
       return false;
     }  

})

Comments

0

count the click

var cnt = 0;
$("#btn").click(function(){

    for(var i=cnt; i<pack_img.length; i++) {
        if(i != pack_img.length-1){
            console.log(pack_img[i]);
            cnt++;
            break;
        }else{
            console.log(pack_img[i]);
            cnt = 0;
            break;
        }

     }  

})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.