AlexJaa
AlexJaa

Reputation: 389

jquery break loop onclick and continue

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. :)

Upvotes: 1

Views: 2695

Answers (3)

HoangHieu
HoangHieu

Reputation: 2840

Try this :

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

    if(_index < pack_img.length){
         _index ++;
    }else{
         _index = 0;
    }
    alert(pack_img[_index ]);
});

Upvotes: 4

jhyap
jhyap

Reputation: 3837

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;
        }

     }  

})

Upvotes: 0

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

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;
     }  

})

Upvotes: 1

Related Questions