Theepan K. Theepan K. - 6 months ago 13
jQuery Question

I need to run specific code for 3 times only in javascript

I need to animate a sliding with jquery. but only for 3 times. I wrote this code. But this more than 3 times. Please help me to fix or give different codes. Thanks in advance.

$(document).ready (function () {
var i=0;
while (i<3) {
$('a.nextbtn').click (function () {
$('ul.post-cat-sliding').stop().animate({"left": "-=596"},1500);
});
i++;
}
});


and also i have previous button.. so if i click previous button slide should go back.

Answer

With your current code you are actually attaching 3 click-events with a single button rather than limiting it to three clicks. So with current code I think your slider will be passing 3 slides with one click.

Try the code down-below:

$(document).ready (function () {
   var i=0;
   $('a.nextbtn').click (function () {
      if(i < 3) {
         $('ul.post-cat-sliding').stop().animate({"left": "-=596"},1500);
         i++;
      }
   });
});