1

I am trying to animate a list item sequentially one at a time repeatedly. Where I have a list containing some list items. What I want to do is use javascript to animate each list item one at a time. I also have to remove the animation from the previous item when it animates the next one. The problem is I am not used to setIntervals or setTimeout functions. I am a beginner in javascript.

  const ThumbnailSlider = document.querySelectorAll('.thumbnail-slider li');

    setInterval(() => {
      ThumbnailSlider.forEach( (item, i) => {
      const ms = (i+1) * 2000;
      setTimeout(() => {
        item.classList.add('active')
      }, ms);
    });
    }, 2000);
  .thumbnail-slider {
     position: relative;
     height: 100%;
     width: 100%;
     }
    .thumbnail-slider li {
     position: relative;
     height: 100%;
     width: 100%;
     }
     .thumbnail-slider li.active {
     background: cyan;
     }
    <ul class="thumbnail-slider">
            <li>list item one</li>
            <li>list item two</li>
    </ul>



  



  

I know this javascript is not enough as I am not removing the active class anywhere using .classList.remove.I also know about toggle.

Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
naveen
  • 223
  • 1
  • 2
  • 11

1 Answers1

0

You can try something like below :-

setTimeout alone should suffice. We will add new class to current element and remove the class for the previous element.

const ThumbnailSlider = document.querySelectorAll('.thumbnail-slider li');

let previousItem;
function animate(){
  ThumbnailSlider.forEach( (item, i) => {
  const ms = (i+1) * 2000;
  setTimeout(() => {
    previousItem?.classList.remove('active');
    item.classList.add('active')
    previousItem = item;
    if(i===ThumbnailSlider.length-1){
    animate();
    }
  }, ms);
});
}

animate();
.thumbnail-slider {
 position: relative;
 height: 100%;
 width: 100%;
 }
.thumbnail-slider li {
 position: relative;
 height: 100%;
 width: 100%;
 }
 .thumbnail-slider li.active {
 background: cyan;
 }
<ul class="thumbnail-slider">
        <li>list item one</li>
        <li>list item two</li>
        <li>list item third</li>
        <li>list item fourth</li>
        <li>list item fifth</li>
</ul>
Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
  • wow, that was quick. thankyou! But if I want to do this repeatedly? I will have to use setInterval right? because this is just one-time animation. I want this to happen infinitly. – naveen Mar 20 '21 at 13:11
  • You can do it via recursion. Updated in the answer. There is a possible answer with `setInterval` too I think. – Lakshya Thakur Mar 20 '21 at 13:16
  • It's working! Thanks. I learned a lot from this. – naveen Mar 20 '21 at 13:19