0

so i was trying to build an inner HTML counter to a specific number wich gets activated when it is in viewport. My code works fine but only on the last of the 3 elements in my ".countarea" Section. When i use console.log it shows all of my 3 divs. Why is only working on the last div?

//Counter Animation
let counter = document.querySelectorAll(".counter");
console.log(counter);
counter.forEach((counter) => {
    counter.innerText="0";
    updatecounter = () => {
        let i = +counter.innerText;
        let target = +counter.getAttribute("data-target");
        let increcement = target / 15000;

        if (i < target) {
            counter.innerText = Math.ceil(i + increcement);
            setTimeout(updatecounter);
        }  else {
            counter.innerText = target;
        }
    }
}); 

let countarea = document.querySelector("section.countarea");

function isInViewport () {
    if (
        countarea.getBoundingClientRect().top < this.window.innerHeight &&
        countarea.getBoundingClientRect().bottom > this.window.innerHeight
        ) {
        updatecounter();
        } else {console.log("false")}
};

window.addEventListener("scroll", isInViewport) ;
Cl3mi
  • 1
  • 1
    It is because `updatecounter` is a variable set over and over again in the loop and it will be whatever the last one is when it is done looping. The call `updatecounter();` is not magically going to call every function you created. – epascarello Jun 06 '22 at 14:51
  • http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html – Quentin Jun 06 '22 at 14:53
  • first you could use `consol.log(...)` to see what you have in variables and which part of code is executed. You would see that you never run `updatecounter()` – furas Jun 06 '22 at 15:06

0 Answers0