Search code examples
javascripthtmlcsssettimeoutsetinterval

JavaScript: animate list item sequentially one at a time repeatedly


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.


Solution

  • 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>