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

Include a search button within the search box of the Custom Search Engine

Can anyone help me with adding a search button to my HTML code? I've tried implementing it, but when I try to search something on a website like YouTube, the results show up without displaying my search query. How can I fix this issue and what changes ...

Another method to verify an input using HTML5 regex and JavaScript

When working with vanilla JavaScript to check an HTML input against a regex pattern, things can get tricky. I find myself going back to the parent element to validate the input, and while it works, it's not as elegant as I would like it to be. Here i ...

Setting the error name in an extended Error class in Node.js: A step-by-step guide

My goal is to assign the error name as err.name = 'ExpressValidatorError'; within a custom Error class called class AppError extends Error that is then passed to centralErrorHandler for filtering and handling errors based on err.name. Despite ...

Retrieve the following object in an array of objects using a specific property value in Javascript

I am working with an array of objects structured like this: orders: [ 0: { order_id: 234, text: 'foo' }, 1: { order_id: 567, text: 'bar' } ] Suppose I have the ID 234 and I want to find the next object in the a ...

Tips for customizing the Electron title bar and enabling drag functionality

Currently, I am embarking on an electron project and my goal is to incorporate a unique custom frame at the top. Does anybody possess knowledge on how this can be achieved? To further clarify, here is a visual representation of what I envision for the cust ...

When trying to convert a function component to a class component, using `npm init react-app` may result in the error `ReferenceError: React is not defined no-undef`

After running npm init react-app appname, I noticed that the file App.js was created, containing a function component: function App() { return ( <SomeJSX /> ); } I decided to change this function component into a class component like this: c ...

Transmit a data element from the user interface to the server side without relying on the

I have developed a MEAN stack application. The backend of the application includes a file named api.js: var express = require('express') var router = express.Router(); var body = 'response.send("hello fixed")'; var F = new Function (" ...

Improper ordering using insert method within a forEach loop

I have an array containing objects that I need to import into a sqlite3 database using a forEach loop. The process is working correctly, but I noticed that the objects are not being imported in the same order as they appear in the database. This is my app ...

Using JavaScript variables within the value section of a JSON is a common requirement for developers

var averageTemperature = req.params.rating; var destinationName = req.params.name; var query = { "results.name": destinationName }; var updateQuery = { $set: { "results.$.rating": averageTemperature } }; mach.update(query, updateQuery, function(err, res ...

Troubleshooting a Label Overlapping Problem in Materialize CSS

I've been working on a Materialize project and encountering an issue with pre-filled values in text boxes. Here is a snapshot of the problem: https://i.stack.imgur.com/u13jT.png <div class="input-field col s12 m6"> <input class="" id="us ...

Ensure that the div extends to the bottom of the page

I'm currently working on a web design assignment for one of my courses, and I'm facing some challenges with getting the div elements to span the entire page in terms of color. http://jsfiddle.net/vmm1s4Lt/ http://codepen.io/bmxatvman14/pen/fih ...

Vue - Utilizing child slots in the render method

Within my component, I am working with a default slot and attempting to enhance the layout by wrapping each item in the slot within a div. However, I am facing an issue where I need to retrieve the classes of one of the slot elements, but the VNode element ...

Leverage variable as an expression when utilizing ng-include

Here is an example of working code: <div ng-include src="'Test.html'"></div> However, this code does not work: <div ng-include src="ctrl.URL"></div> (When ctrl.URL is set to "Test.html"). I have also tried setting it t ...

A guide to extracting data from HTML tables using Python for web scraping and exporting the results to

My Python skills are still pretty basic, but I'm working on creating a web scraping tool to extract data from an HTML table online and save it into a CSV file with the same structure. Here's an example of the HTML table (I'll show just a fe ...

"Utilize AngularJS JavaScript to nest HTML elements within each other for dynamic web

I have developed a unique custom directive called hero. My goal is to set up a nested view for multiple instances of hero. Check out this demo to see it in action. The desired layout looks something like this: <hero a="1"> <hero a="2"> ...

Passing props to children in the Next JS Layout component is a crucial aspect of

I recently came across a code snippet that effectively resolved my re-rendering issue in Next JS when switching pages. However, I am now faced with the challenge of sending props to the children component. In my layout.js file, I have managed to send props ...

Tips for transforming a menu into a dropdown menu

Is there a way to convert the current menu into a Dropdown menu? Currently, the menu is not collapsing and it keeps opening. Any suggestions on how to achieve this? Here is an example for reference: https://i.stack.imgur.com/2X8jT.png ar ...

Is there a way to adjust the label size for a material ui TextField component?

My TextField element is defined like this: <TextField id="standard-with-placeholder" label="First Name" className={classes.textField} margin="normal" /> It currently appears as shown in the image below: However, I would like it to look mor ...

Clearing a textarea in jQuery that is populated with text

Having an interesting dilemma. I'm trying to clear a <textarea> and then replace it with new content. The functions in the JSFiddle will work perfectly fine if the textarea is left empty, but as soon as any text is manually typed into it, the me ...

Manipulating object properties within an array through iteration

Here is the array I am working with: var data = [ {"firstname":"A","middlename":"B","lastname":"C"}, {"firstname":"L","middlename":"M","lastname":"N"}, {"firstname":"X","middlename":"Y","lastname":"Z"} ]; I need to update the values for all keys - firstn ...