jQuery counter no longer updates when scrolling

I'm having trouble with my jQuery counting function when using the scroll feature on a specific div ID. The numbers freeze if I keep scrolling before they finish updating on the screen.

Whenever I scroll to the defined div ID, the counting function kicks in. However, if I scroll again, it freezes the numbers and only continues counting once I stop scrolling.

Is there a way to scroll to a certain div and activate the counter function without it stopping during further scrolling?

//Counter
$(window).scroll(function () {
 var a = 0;

  var oTop = $('#stats').offset().top - window.innerHeight;
  if (a == 0 && $(window).scrollTop() > oTop) {
    $('.number').each(function() {
      var $this = $(this),
      countTo = $this.attr('data-count');
      $({
        countNum: $this.text()
      }).animate({
          countNum: countTo
        },

        {

          duration: 2000,
          easing: 'swing',
          step: function() {
            $this.text(Math.floor(this.countNum));
          },
          complete: function() {
            $this.text(this.countNum);
          }

        });
    });
    a = 1;
  }

});
#stats{
    background: #222629;
    width: 100%;
    height: auto;
}
#stats .space{
    padding: 10px;
    height: auto;
}
.sectiontitle {
  margin: 30px 0 0px;
  text-align: center;
  min-height: 20px;
}

.sectiontitle h2 {
  direction: rtl;
  font-size: 30px;
  color: #222;
  margin-bottom: 0px;
  padding-right: 10px;
  padding-left: 10px;
}
.headerLine {
  width: 160px;
  height: 2px;
  display: inline-block;
  background: #101F2E;
}



//Counter
.holder{
    width: 50% !important;
}
.counter{
  display: flex;
  margin-top: 3%;
  flex-direction: row;
  justify-content: center;
  flex-wrap: wrap;
}
.counter .item1{
  vertical-align: middle;
  width: 16.66%;
  height: 100%;
  text-align: center;
  padding: 0;
  margin: 20px 0;
}
.counter .item1 i{
  color: #fff;
  font-size: 4em;
  text-shadow: 1px 1px 1px #ccc;
}
.counter .item1 p.number{
  color: #fff;
  font-size: 3em;
  text-shadow: 1px 1px 1px #ccc;
}
.counter .item1 p.label{
  color: #fff;
  font-size: 1.1em;
  text-shadow: 1px 1px 1px #ccc;
  text-transform: lowercase;
}
.counter .item1:hover i, 
.counter .item1:hover p{
  color: #cecece;
}

@media (max-width: 786px){
  .counter .item1 {
     flex: 0 0 50%;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/><br/>
<br/>
<br/>
<br/>
<br/>
<br/><br/>
<br/>
<section id="stats">
         <div class="space">
            <div class="sectiontitle">
                <h2 style="color: white;">פרוייקטים וסטטיסטיקות</h2>
                <span class="headerLine" style="background-color: white;"></span>
            </div>
             
             
             
             
             <div class="holder">
              <div class="counter ">
                <div class="item1" style="background-color:">
                  <i class="fas fa-laptop" style="font-size: 2em; color: white; text-shadow: 1px 1px 1px #ccc;"></i>
                  <p data-count="5743" class="number">0</p>
                  <p class="label">פיתוח בשעות</p>
                </div>
                <div class="item1">
                  <i class="far fa-smile" style="font-size: 2em; color: white; text-shadow: 1px 1px 1px #ccc;"></i>
                  <p class="number" data-count="8">0</p>
                  <p class="label">לקוחות מרוצים</p>
                </div>
                <div class="item1">
                  <i class="fas fa-briefcase" style="font-size: 2em; color: white; text-shadow: 1px 1px 1px #ccc;"></i>
                  <p data-count="6" class="number">0</p>
                  <p class="label">פרוייקטים שסויימו</p>
                </div>
                <div class="item1">
                  <i class="fas fa-coffee" style="font-size: 2em; color: white; text-shadow: 1px 1px 1px #ccc;"></i>
                  <p data-count="53" class="number">0</p>
                  <p class="label">כוסות קפה</p>
                </div>
              </div>
             </div>
             
             
             
         </div>
     </section>

Answer №1

Following @Atul's suggestion, transforming var a = 0; into a global variable resolves the problem. It might be even more effective to define it as a boolean.

<script>
  //Counter
  var a = 0;
  $(window).scroll(function () {

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlock the Power of Typescript: Using the Browser Console to Access Functions

Scenario Within the file ts/app.ts, the following function exists: function foo() { console.log('Hello Word'); } After successful compilation with Webpack, it generates a file named bundle.js. To load this file, use the following script tag ...

Parsing JSON data received from Angular using JSP

As I navigate through my Angular application, I'm encountering a challenge when trying to save data on the server side using JSP. The issue arises when Angular's $save method sends the object data in a JSON format that is not familiar to me. This ...

Is there a sophisticated CSS compressor that can eliminate unnecessary code and separate identical rules with commas?

Consider this input{margin:0}body{margin:0;background:white} can also be written as input,body{margin:0}body{background:white} or like this input,body{margin:0}body{margin:0;padding:0} and simplified to input,body{margin:0}body{padding:0} Bottom Li ...

The external embedded CSS seems to be missing from index.html after the Docker build process

My Vue/Webpack application includes an embedded CSS link in my index.html file that references an external source. Here is an example snippet: <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" con ...

Strange behavior in Angular's http response

When I make a call to my API and receive a JSON response, the code snippet below illustrates how I handle it: getAllLearn() { this.learnService.getAllLearn().subscribe(res =>{ // The console log shows that res.featured only has one index: ( ...

The communication between the Next.js and Node.js servers is being obstructed as the request body fails

Could you lend me a hand with this issue? Here is the function being called: function apiCreate(url, product) { console.log('Posting request API...' + JSON.stringify(product) ); fetch(url, { dataType: 'json', method: 'post ...

The Angular Function has stopped working out of the blue following the implementation of Jquery Ajax

As a newcomer to php programming, I am facing an issue with my Angular Function not functioning properly when incorporating a jQuery ajax method post to update values in the database. Below is my angular code within HTML: <tfoot ng-app="kembalianApp" ...

Is it possible to adjust the color and placement of the CircularProgress component?

Utilizing the CircularProgress component provided by Material has been a goal of mine. In my efforts to achieve this, I developed a component with the intention of customizing its color: import React, { Component } from 'react'; import { withSt ...

Is it possible to pass a parameter to an NGXS action that is not the Payload?

I am working on implementing an Ngxs action that includes a parameter in addition to the payload. This parameter is used to determine whether or not a notification should be sent. @Action(UpdateUser) async UpdateUser( ctx: StateContext<ProfileStat ...

Combining Nested Objects in MongoDB

I have searched extensively for a solution but I am struggling to find a resolution to my issue. I have two MongoDB (Node.JS) collections: user & statistics. My goal is to merge the results using aggregate. Below are the structures of the collection ...

What is the best way to assign a value to process.env within an npm script?

After creating a new Vue app (using Vite) with npm init vue@latest and selecting Playwright for e2e tests, the configuration file was generated with a field for setting headless mode: const config: PlaywrightTestConfig = { // ... use: { // ... ...

The e.currentTarget attribute in Material UI buttons is a key element that

I am facing an issue with implementing three tabs and buttons in my project. Each button should display a corresponding message when selected I have tried using e.currentTarget but no success so far. Can someone guide me on how to resolve this problem? You ...

Arranging buttons in a row with Bootstrap 5

Struggling to align the buttons on my webpage side by side in the center, I've tried two Bootstrap 5 classes but they're not achieving the desired look: https://gyazo.com/c23f2eade4614380aec547b11e61387a https://gyazo.com/e40a678b02c9f641f746b1c ...

Arrange the side by side display of uploaded image previews

Could someone please assist me with aligning my image upload preview in a row, similar to a brand/partners slider? The current preview output is not displaying as desired. Here is the code I have: <div class="image-gallery"> <div class ...

Searching for an object in Vue 3 Composition API and displaying its contents

Experiencing a challenge with my first Vue.js project, seeking assistance in resolving the issue. Upon receiving a response from my API, I retrieve a list of projects and aim to locate the one matching the ID provided in the URL parameter. A peculiar error ...

Refreshing the dropdown selection to a specific option using AngularJS and either JavaScript or jQuery

Currently, I am facing an issue with resetting the select tag to its first option. I have implemented Materialize CSS for styling purposes. Despite my efforts, the code snippet below is not achieving the desired outcome. Here is the JavaScript within an ...

Having trouble with Semantic UI Modal onShow / onVisible functionality?

Seeking assistance with resizing an embedded google map in a Semantic UI modal after it is shown. After numerous attempts, I have narrowed down the issue to receiving callbacks when the modal becomes visible. Unfortunately, the onShow or onVisible functio ...

Adjust the size of the frame by dragging the mouse cursor to change both the width

I'm a bit lost on where to direct this question, so I decided to include the html, web, and css categories (though I suspect it's related to css). The task at hand involves creating an html page with a fixed header, while the content area compris ...

Retrieve a variable from the context and assign it to the Angular scope

I'm having trouble accessing the sourcePath in the controller $scope. This is the code I have: (function() { var sourcePath; sourcePath = 'app/assets/javascripts/shared/controllers/some_controller.coffee'; angular.module("shared"). ...

What is the process for setting up both an open and closed status for my accordion?

After browsing through multiple threads on accordions, none seem to match my current structure which I believed was effective. In an attempt to learn and build elements from scratch, I created the following accordion with some help from Google and experi ...