Home > Mobile >  Not Able to Iterate in Each loop to change Opacity of Set of Elements
Not Able to Iterate in Each loop to change Opacity of Set of Elements

Time:02-10

Can you please take a look at this demo and let me know why I am not able to make an infinity loop to change opacity of each <p> (like fadeIn fadeOut functions ). I am trying to mix the fadeIn and fadeOut function with display none utility.

$(function() {

  $("p").each(function() {
    $('p').animate({
      opacity: 0
    }, 500, function() {
      $('p').css('display', 'none');
      $(this).css('display', 'block');
      $(this).animate({
        opacity: 1
      }, 500);
    });
  });
});
p {
  color: #008080;
  background-size: 40px;
  padding: 10px;
  font-size: 30px;
    display: none;
    opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>This is the fiest step</p>
<p>This is the second step</p>
<p>This is the third step</p>
<p>This is the forth step</p>

CodePudding user response:

Each callback of .each( runs synchronously - each one will run immediately without waiting for the prior one to finish. You should use .promise() to have a callback wait for the animation to complete before proceeding - but since you also want to loop endlessly, and not just once, you'll also need a completely different strategy. Consider having a persistent index variable that you reassign using modulo, and whose associated element's animation you await inside a loop.

(async() => {
  const ps = $('p');
  let i = 0;
  while (true) {
    await ps.eq(i).animate({
      opacity: 0
    }, 500, function() {
      $('p').css('display', 'none');
      $(this).css('display', 'block');
      $(this).animate({
        opacity: 1
      }, 500);
    }).promise();
    i = (i   1) % ps.length;
  }
})();
p {
  color: #008080;
  background-size: 40px;
  padding: 10px;
  font-size: 30px;
  display: none;
  opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>This is the fiest step</p>
<p>This is the second step</p>
<p>This is the third step</p>
<p>This is the forth step</p>

  • Related