correct way to interpolate two jquery animations

Viewed 28

I have a list of elements and I want to:

  • show the first element,
  • change its color
  • iterate to the next one

I tried to implement this rewriting a function that I have written that just changed the color of each li element but I get to no point and I see no errors that can help me to debug.

The code:

function highlight() {
  // Add highlight class to first li element that isn't highlighted
  $("#risultato li h2:not(.text-danger)").first().show('slow', function() {
    setTimeout(function() {
      $(this).addClass('text-danger')
    }, 1500);
  });

  // Check if any more li exist without the highlight class
  // (This avoids an endless loop)
  // Repeat process
  if ($("#risultato li h2:not(.text-danger)").length != 0) {
    setTimeout(function() {
      highlight();
    }, 1500);
  } else {
    //do something when the animation has ended
    //not in scope for the question
  }
}



$(function() {
  highlight();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="risultato">
  <li style="display: none">
    <h2>Step1</h2>
  </li>
  <li style="display: none">
    <h2>Step2</h2>
  </li>
  <li style="display: none">
    <h2>Step3</h2>
  </li>
  <li style="display: none">
    <h2>Step4</h2>
  </li>
  <li style="display: none">
    <h2>Step5</h2>
  </li>
  <li style="display: none">
    <h2>Step6</h2>
  </li>
</ul>

What am I missing here?

1 Answers

You're targeting and trying to show the h2 elements, yet it's the li which are hidden. You can also simplify the logic slightly to perform the check and queue the next item in a single iteration, like this:

let $ul = $('#risultato');
let showNextLi = () => {
  $ul.find('li:hidden:first').show('slow', function() {
    let $li = $(this);
    if ($li.next().length) {
      setTimeout(() => {
        showNextLi();
        $li.addClass('danger')
      }, 1500);
    } else {
      console.log('complete, do something else here...');
    }
  });
}

showNextLi();
#risultato li { 
  display: none; 
  list-style-type: none;
}
#risultato li.danger { 
  color: #C00; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="risultato">
  <li><h2>Step1</h2></li>
  <li><h2>Step2</h2></li>
  <li><h2>Step3</h2></li>
  <li><h2>Step4</h2></li>
  <li><h2>Step5</h2></li>
  <li><h2>Step6</h2></li>
</ul>

Related