Home > Software design >  Iterating over each child and apply a css property based on time passed
Iterating over each child and apply a css property based on time passed

Time:04-05

earlier I made a post: https://jsfiddle.net/dqj1x89z/

What I wanted to do is to apply a class on children elements based on the time that has passed, until now I managed to do something like that, besides what I already have there:

var childNodes = $('.tbi-phone-verification-loader').children();

function startTimer() {
        timerInterval = setInterval(() => {
        timePassed = timePassed  = 1;
        timeLeft = TIME_LIMIT - timePassed;
        document.getElementById("base-timer-label").innerHTML = formatTime(timeLeft);
        var intervalId = window.setInterval(function() {
            // childNodes.each(function(){
            //     $('.tbi-phone-verification-loader div:nth-child(i)').css("background","red");
            // })
            for(var i = 0; i <= childNodes.length; i  ) {
            $('.tbi-phone-verification-loader div:nth-child(' i ')').css("background","red");
        }
        }, 10000)
        // var formattedTimeLabel = $('.base-timer__label').html();
        // formattedTimeLabel.replaceWith(`${formatTime(timeLeft)}`);

        //  if (timeLeft === 0) {
        //     onTimesUp();
        //     }
        }, 1000);
    }

I tried using for but it doesn't work, after 10 seconds all the circles are going red, I want every 10 seconds to fill a circle with the specified color.

CodePudding user response:

Check this out: https://jsfiddle.net/ck02pozu/

What I added

  1. Made an array from all of the divs in the document: let circles = Array.from(document.getElementsByTagName("div")).

  2. Set a index for the array which will increased every-time 10 seconds have passed: let circleIndex = 1 Note that I set it to 1 instead of 0 since you have another div which isn't a circle (at the start of the document).

  3. Added a condition which will check if the seconds are divisible by 10 each time that the formatTime function have been called.

  4. If the condition turns out the true, modify the current circle's background to red and increase circleIndex by 1.

Getting the last animated circle

This is after reading the OP's comment

  1. initialize an empty variable: let lastCircleIndex
  2. Before modifying circleIndex's value by 1: lastCircleIndex = circleIndex

Now check the console, lastCircleIndex will always be -1 away from circleIndex.

P.S: I edited the link in the above to include this last animated circle example.

  • Related