javascripthtmlcss

Loop for nth-child and set style doesn't work


I have with class fade-in-row. I want for each nth-child with fade-in-row class to have animation delayed by 0.25s. I had this:

.fade-in-row{
  animation: fadeDown 0.5s both;
}
.fade-in-row:nth-child(2){
    animation-delay: 0.5s;
}
.fade-in-row:nth-child(3){
    animation-delay: 1s;
}
.fade-in-row:nth-child(4){
    animation-delay: 1.5s;
}
.fade-in-row:nth-child(5){
    animation-delay: 2s;
}

But it's capped at 5. I can add more, but i need a lot of them.

I used google, and now i know about querySelector. Now my code in OnLoad() (which is used in ) is this:

for (let i = 1; true;i++){
    if (document.querySelector(`.green-text :nth-child(${i})`) == null) break
    document.querySelector(`.green-text :nth-child(${i})`).children[0].style.animationDelay = i/4;
}

And needed part of html is:

<div class="green-text">
    <div class="fade-in-row">
        <h1>Foo</h1>
    </div>
    <div class="fade-in-row">
        <h1>Bar</h1>
    </div>
    <div class="fade-in-row">
        <h1>Some text</h1>
    </div>
    <div class="fade-in-row">
        <h1>More Text</h1>
    </div>
</div>

No errors in console but it doesn't work.


Solution

  • I have used onload event along with querySelectorAll. You can trigger the animation on other events as well. Something like:

    function animateDelay() {
      const fadeInRows = document.querySelectorAll('.green-text .fade-in-row');
      fadeInRows.forEach((element, index) => {
        element.children[0].style.animationDelay = `${index * 0.25}s`;
        element.children[0].classList.add('fade-in-row-animated');
      });
    }
    
    window.addEventListener('load', animateDelay);
    .fade-in-row {
      /* Commented this ----> animation: fadeDown 0.5s both; */
    }
    
    @keyframes fadeDown {
      0% {
        opacity: 0;
        transform: translateY(-20px);
      }
      100% {
        opacity: 1;
        transform: translateY(0);
      }
    }
    
    .fade-in-row-animated {
      animation: fadeDown 0.5s both;
    }
    <div class="green-text">
        <div class="fade-in-row">
            <h1>Foo</h1>
        </div>
        <div class="fade-in-row">
            <h1>Bar</h1>
        </div>
        <div class="fade-in-row">
            <h1>Some text</h1>
        </div>
        <div class="fade-in-row">
            <h1>More Text</h1>
        </div>
    </div>