Animate numbers in response to scroll with JQuery

I am currently working on a project where I need to create a counter that triggers at a specific scroll value. Essentially, I want users to see animated numbers incrementing from 0 to a pre-defined number once they reach a certain point while scrolling.

Here is the progress I have made so far:

$(document).scroll(function(){

    var _scrollTop = $(document).scrollTop();

    if(_scrollTop >= 1490){
        $('.Count').each(function () {
            var $this = $(this);
                jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
                    duration: 3000,
                    easing: 'swing',
                    step: function () {
                        $this.text(Math.ceil(this.Counter)).stop();
                    }
                });
        }); 
    }
}); 

However, the numbers keep refreshing every time I scroll beyond that value. My intention was for the animation to occur only once when the user scrolls past the specified value and then remain at that value in the HTML. Any assistance with this issue would be greatly appreciated.

View the full JS Fiddle here

Answer №1

Once the conditions are met for starting a counter using the scroll function, you have the option to completely unbind the function so it doesn't run again:

if(_scrollTop >= 1490){
    $(document).unbind('scroll');
    //......

This will remove all attached scroll events on the document. If you have multiple scroll events implemented, you can save a specific delegate in a variable and then unbind that instead.

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

Dynamic Component Interactions in VueJS using Mouse Events

Just starting out with Vue and other frameworks, so my approach may not be very "Vue-like". I am attempting to create a versatile button component that can have different behaviors based on a prop, in order to maintain just one button component. The desir ...

"Exploring the process of integrating a controller into an external HTML file using AngularJS

I'm relatively new to AngularJS. In my web app, I have a set of buttons: index.html <button class="aButton">a</button> <button class="bButton">b</button> <script> $(document).ready(function(){ $(".aButton"). ...

Why am I experiencing a problem with my ajax call only working once when I submit forms that are rendered with @Html.Render

I have a scenario where my index page loads with two partial views, each containing an ajax call that filters content based on date. The issue I'm facing is that the ajax call only works once successfully, and subsequent attempts cause a full page ref ...

unable to display data through the web service

The functionality of this code is correct, but it seems to not be displaying records. When the record is retrieved from the file and shown in an alert, everything works fine. $j().ready(function(){ var result =$j.ajax({ ...

Mastering the stable usage of $watchIncorporating reliable

Please review the following code snippet: front_controller $scope.month=monthNames[$scope.currentmonthnumber]; monthyeartransfer.setvalue($scope.month); $scope.monthchange = function(m) { $scope.month = m; monthyeartransfer.setvalue($scope.month); ...

What is the most effective way to showcase dynamic labels and their values in a pie chart using chart.js?

Here is my current Pie chart https://i.sstatic.net/ABwVv.png, however, I am aiming for this type of chart https://i.sstatic.net/TdJ21.png I am trying to dynamically display labels and label values in a pie chart using Chart.js. The issue with my code ...

Utilizing an event emitter to read from a text file

I have a text file with multiple lines containing data such as pepperoni pizza, pizza margherita, etc. I am trying to create an EventEmitter that will trigger specific events based on the content of the file. For example, if the word "pepperoni" is found ...

Array containing two objects in a two-dimensional format

In the example provided, I am working with a 2D array. Link to the example: https://codesandbox.io/s/v0019po127 I am noticing different results depending on whether I use the browser console or Codesandbox's console. I have attempted using JSON.str ...

Guide to Embedding StencilJS components in a Storybook React Application

I am currently in the process of integrating Stencil and Storybook within the same project. While following this setup guide and this one, I encountered a step that requires publishing the component library to NPM, which is not my desired approach. In my ...

JSON object containing multiple elements in JavaScript

I have a JavaScript JSON object const student = { name: "bob", age: 7, grade: 6 } and I can send it to my Web API using the axios POST command with JSON.stringify(student) To build multiple student objects from an array by looping through and p ...

Improprove the performance of external banner ads by utilizing asynchronous loading or caching techniques

My website is slick, elegant, and loads quickly - that is until the banner ads come into play! A delay of up to 10 seconds in loading occurs due to waiting for the ads, which is frustrating considering the effort I put into optimizing the rest of the site. ...

Exploring the depths of Vue.js routing through nesting

My Current Route is function route(path, view) { return { path: path, meta: meta[path], component: resolve => import(`pages/${view}View.vue`).then(resolve) } } route('/', 'Home'), route('/help', 'Help ...

Guide to cycling through an array in Angular template in order to display assorted colored tiles with a consistent pattern

View images in tile format Here are the specific colors assigned to each tile when looping through 0 to 11, where there are 12 records in the array for each tile: - Red color for tiles at index: 0, 4, 8, and 12 - Green color for tiles at index: 1, 5, an ...

Developing gaps or margins among table components

Struggling to create spacing between text and an image in an HTML email, but the image just won't budge no matter what I do. Check out my Fiddle here: https://jsfiddle.net/rwcgs0g8/ All I want is for the red "Download your free" image to shift down ...

Fade in elements as the cursor moves, without hovering over a specific element

I'm working on implementing a fade-in effect for content when the mouse moves (similar to Google's homepage), but I'd like to avoid this behavior if the cursor is hovering over a specific div. Here are the basics: $("html").hover(function( ...

Is there a way for me to retrieve PHP variable data from an AJAX response?

Looking for assistance with my program that involves posting data through radio buttons and sending it to a PHP page using jQuery AJAX. I need help retrieving the variable data from this page so that I can utilize it on the initial page. Can anyone offer a ...

Discovering the maximum value and fetching it from an array

Can you help me identify the array element with the highest 'conversion' value? var barTextData = [ { term: "Roof", clicks: 11235, conversion: 3.12 }, { term: "Snow", clicks: 6309, conversion: 4.45 }, { term: "Chains" ...

Unable to uncheck all checkboxes

My checkbox list has a checkbox at the top to select all checkboxes, but after selecting them all, I encounter issues in clearing them. Here is the code snippet for the implementation: class App extends React.Component { state = { checked: undefined } ...

The troubleshooting of debugging javascript remotely on IntelliJ with the JetBrains Chrome extension is proving to be unsuccessful

I've been attempting to set up a debugger for some JavaScript files that I'm working on in IntelliJ (version 2020.1.4). Following the guidelines provided here Debug with JetBrains Chrome extension, I believe I have successfully completed all the ...

Leveraging the power of jQuery and Bootstrap within an application customizer and across various web

Deciding to utilize Bootstrap for customization is a personal choice of mine. Currently, I am considering incorporating jQuery and Bootstrap in both the application customizer and multiple web parts. I am seeking advice on the most effective approach for ...