Durubie Durubie - 1 month ago 5
HTML Question

jQuery animate loop not working properly



for (i = 0; i < 100; i++) {
$('#container').animate({ 'opacity': 0 }, 1000, function () {
$(this).text('Just Do It.');
}).animate({ 'opacity': 1 }, 1000, function () {
$(this).animate({ 'opacity': 0 }, 1000, function () {
$('#container').text('Nike');
$('#container').animate({ 'opacity': 1 }, 1000);
});
});
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">Nike</div>







$('#container').animate({ 'opacity': 0 }, 1000, function () {
$(this).text('Just Do It.');
}).animate({ 'opacity': 1 }, 1000, function () {
$(this).animate({ 'opacity': 0 }, 1000, function () {
$('#container').text('Nike');
$('#container').animate({ 'opacity': 1 }, 1000);
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">Nike</div>





So the goal of my code was to successfully loop a fade in and fade out effect except by using opacity and animate, The code without the for loop runs fine by itself but as soon as I try to loop it, it just keeps looping the "just do it" part, if anyone could help me figure this out it would be greatly appreciated.

Answer

Check this example:

var i = -1;
var x = -1;
var max = 100;
var txt = ["Nike", "Just Do It", "BMW"];

anim();

function anim() {
  if (x == max) return;
  x++;
  i++;
  if (i == txt.length) {
    i = 0;
  }

  $('#container').animate({
    'opacity': 0
  }, 1000, function() {
    $(this).text(txt[i]);
  }).animate({
    'opacity': 1
  }, 1000, function() {
    $(this).animate({
      'opacity': 0
    }, 1000, anim);
  });


}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>