简体   繁体   中英

function only runs once even though use forEach() Javascript

I want to make the numbers increase onclick using the snippet that I got and named it "numberIncrease()". But the problem is the function only run for the first h1. I tried console.log inside the forEach loop and it does detect both elements.

Why is it that my code only runs for one of the numbers? the forEach does detect both.counter, but it doesn't show in the code.

Should I try different types of loops?

<button id="button">test</button>
<h2 class="counter" data-count-start="500">788</h2>
<h2 class="counter" data-count-start="333">666</h2>


<script>
let test = true;
const button = document.getElementById('button');
let counter = document.querySelector('.counter');

button.addEventListener('click', function() {
  if (test) {
    document.querySelectorAll('.counter').forEach(counter=>{
      numberIncrease();
      console.log(counter)
    })
  } else {
    console.log('no');
  }

})

function numberIncrease() {
  const counter = document.querySelector(".counter");
  const tl = gsap.timeline();
  const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)")
  .matches;

  animateCount(counter);

  function animateCount(el) {
    const start = removeCommas(el.dataset.countStart);
    const end = removeCommas(el.textContent);

    tl.fromTo(
      el,
      {
        innerText: start,
        "--font-variation-weight": 300,
        scale: reducedMotion ? 1 : 0.99
      },
      {
        innerText: end,
        snap: { innerText: 1 },
        duration: reducedMotion ? 0 : 3,
        ease: "linear",
        onUpdate: () => {
          el.innerHTML = formatNumber(el.innerText);
        }
      }
    ).to(el, {
      scale: 1,
      "--font-variation-weight": 600,
      ease: "elastic.out(1, 0.2)",
      duration: 1.2
    });
  }

  function celebrate() {
    setCelebrateClass(true);
  }

  function setCelebrateClass(enabled) {
    counter.classList.toggle("celebrate", enabled);
  }

  function removeCommas(num) {
    return num.replace(/,/g, "");
  }

  function formatNumber(num) {
    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
  }
}

</script>

You are doing a query selector inside your function, you should pass it as a parameter, te element, and using that parameter i side your function. I barely looked at it, i hope it works, i cant test it cause im on my phone

    <button id="button">test</button>
    <h1 class="counter" data-count-start="500">788</h1>
    <h1 class="counter" data-count-start="333">666</h1>


    <script>
        let test = true;
        const button = document.getElementById('button');
        let counter = document.querySelector('.counter');
        
        function numberIncrease(counter) { //edited line
            if (counter) {//edited line
                const tl = gsap.timeline();
                const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)")
                    .matches;

                animateCount(counter);

                function animateCount(el) {
                    const start = removeCommas(el.dataset.countStart);
                    const end = removeCommas(el.textContent);

                    tl.fromTo(
                        el, {
                            innerText: start,
                            "--font-variation-weight": 300,
                            scale: reducedMotion ? 1 : 0.99
                        }, {
                            innerText: end,
                            snap: {
                                innerText: 1
                            },
                            duration: reducedMotion ? 0 : 3,
                            ease: "linear",
                            onUpdate: () => {
                                el.innerHTML = formatNumber(el.innerText);
                            }
                        }
                    ).to(el, {
                        scale: 1,
                        "--font-variation-weight": 600,
                        ease: "elastic.out(1, 0.2)",
                        duration: 1.2
                    });
                }

                function celebrate() {
                    setCelebrateClass(true);
                }

                function setCelebrateClass(enabled) {
                    counter.classList.toggle("celebrate", enabled);
                }

                function removeCommas(num) {
                    return num.replace(/,/g, "");
                }

                function formatNumber(num) {
                    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
                }

                console.dir(counter);
            } else {
                console.error('Counter not found!') //edited line
            }
        }

        button.addEventListener('click', function() {
            if (test) {
                console.log('yes');
                document.querySelectorAll('.counter').forEach(counter => {
                    numberIncrease(counter); //edited line
                    console.log()
                })
            } else {
                console.log('no');
            }

        })
    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM