Text Animation in jQuery as You Scroll

Issue: 1. The text count animates up and then back down, but it should only count up once and stop. 2. The numbers should default to 0 on page load rather than the target number.

Consider this code snippet...

JQuery:

$(window).scroll(function() {
   var hT = $('#scroll-to').offset().top,
       hH = $('#scroll-to').outerHeight(),
       wH = $(window).height(),
       wS = $(this).scrollTop();
    console.log((hT-wH) , wS);
   if (wS > (hT+hH-wH)){
$('.count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));    
        }
    });
});
        }
});

HTML

<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div id="scroll-to">
<div id="shiva"><span class="count">200</span></div>
<div id="shiva"><span class="count">1000</span></div>
<div id="shiva"><span class="count">853</span></div>
<div id="shiva"><span class="count">154</span></div>
<div id="shiva"><span class="count">10</span></div>
<div id="shiva"><span class="count">87</span></div>
<div style="clear:both"></div>
<div id="talkbubble"><span class="count">1421</span></div>
<div id="talkbubble"><span class="count">145</span></div>
<div id="talkbubble"><span class="count">78</span></div>
<br />
<br />
<br />
</div>

CSS

#shiva
{
  width: 100px;
    height: 100px;
    background: red;
    -moz-border-radius: 50px;
    -webkit-border-radius: 50px;
    border-radius: 50px;
  float:left;
  margin:5px;
}
.count
{
  line-height: 100px;
  color:white;
  margin-left:30px;
  font-size:25px;
}
#talkbubble {
   width: 120px;
   height: 80px;
   background: red;
   position: relative;
   -moz-border-radius:    10px;
   -webkit-border-radius: 10px;
   border-radius:         10px;
  float:left;
  margin:20px;
}
#talkbubble:before {
   content:"";
   position: absolute;
   right: 100%;
   top: 26px;
   width: 0;
   height: 0;
   border-top: 13px solid transparent;
   border-right: 26px solid red;
   border-bottom: 13px solid transparent;
}

.linker
{
  font-size : 20px;
  font-color: black;
}

UPDATE: JSFiddle

Your help in resolving this issue is much appreciated. Thank you.

Answer №1

If you're looking to enhance the initial markup and set a target using a data attribute, here's a suggestion:

Consider implementing this approach:

$('.count').each(function () {
    var newTarget = $(this).attr('data-target');
    $(this).animate({
        Counter: newTarget
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));    
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="shiva"><span class="count" data-target="200">0</span></div>
<div id="shiva"><span class="count" data-target="1000">0</span></div>

Furthermore, it's advised to include a flag in your conditional statement to prevent multiple executions of the counter, potentially resolving the initial issue:

var isCounterRunning = true;
if (wS > (hT+hH-wH) && isCounterRunning ){
isCounterRunning = false;
// continue with the remaining code...
}

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

Ensure that the anchor element's height fills the entire div when using the display:block property

My HTML code is very simple: <div class='mydiv'> <a href='#'>Link</a> <div> As for the CSS: div.mydiv { height: 200px; width: 200px; background-color:red; } div.mydiv a { display:block; color:yellow; b ...

Learn how to create an endless scrolling effect on a static webpage using only pure JavaScript

Looking to achieve an Infinite Page Scroll Effect similar to Twitter without relying on jQuery or any other library, using pure JavaScript. I'm new to JavaScript and need assistance with implementing this effect in search results displayed within a La ...

Building a nested table within a parent table in bootstrap is a breeze

Can you provide guidance on nesting tables in Bootstrap-3? Whenever I attempt it, the second table ends up being displayed after the first one. ...

How can you check the varying font renderings on your phone?

https://i.sstatic.net/z7HcQ.png https://i.sstatic.net/1tH5d.png Having some trouble with the font display on my website. Currently using: font-family: 'Fredoka One', cursive; It's working well on PCs and desktops, but when viewed on a pho ...

Angular HTML is throwing an error related to object arrays

Is there a way to display only specific fields of an array? <div class="form-check" *ngFor="let periodo of filterPeriodos()"> <div>{{periodo.periodos | json}}</div> <input class="form-check-input mr- ...

Problem encountered when trying to simulate a click on a table row in jQuery

DataTables v1.10.0: My challenge is with DataTables v1.10.0 where I am attempting to trigger a click event on the first row. Everything else in the table is functioning correctly. I experimented with adding a class instead of triggering the click event an ...

angular-library.js:6 Uncaught TypeError: Unable to access the 'toLowerCase' property of an undefined value

$scope.searchCat = function(){ $scope.searchArray = []; const searchField = document.querySelector('#search input[type="search"]'); if(searchField){ $scope.searchTerm = searchField.value.toLo ...

The canvas is responsive to keyboard commands, however, the image remains stationary and unaffected

As I delved into the basics, incorporating canvas, CSS, and JavaScript, a question arose: should the image be housed in the HTML or the JavaScript code? Following this, I added a background color to the canvas and defined properties of the canvas in JavaSc ...

Tips for aligning an element with another element's position

Is it possible to have the new hello button displayed in exactly the same position as the previous one after clicking the Hello button? const rightDiv = document.querySelector('#rightDiv'); const leftButton = document.querySe ...

forward to a different link following the backend script execution

I am facing a challenge with the signup.php page which includes a Facebook login button. The structure of the page is as follows: <?php if(!isset($_SESSION['logged_in'])) { echo '<div id="results">'; echo '<!-- ...

AngularJS triggers ng-change event only when there are updates in the text box values

In my application, I have a text box that utilizes a custom directive called change-on-blur for field validation upon tab out. The issue arises when typing in the text box such as initially entering 'ABCD', deleting 'D', and retyping &a ...

Hidden button trigger is malfunctioning

I am attempting to activate a hidden button, but the event does not seem to be triggering. Here is the code snippet: <div class="dyn-inp-group"> <div class="dyn-inps"> <div class="form-group form-group-options col-xs-12 dyn-inp" ...

"Resolving an inconsistency problem with the Vary header in Htaccess

Could someone help me identify the issues in my htaccess code? I'm encountering errors: This response is negotiated, but doesn't have an appropriate Vary header. The resource doesn't send Vary consistently. ## add vary header <IfModule ...

Can jQuery be utilized similarly to Ruby in an IRB mode setting?

Exploring the capabilities of irb has been such a time-saver for testing my ruby code. I'm curious if there are similar tools like Firebug that allow quick checking and debugging? ...

Is it possible for me to use Tailwind CSS in a .css file?

When I began my exploration of Tailwind with react, I encountered a hurdle. I have a strong dislike for inline CSS due to its subpar code readability. Is there a method available that would allow me to write Tailwind CSS in a separate file and then import ...

What is the best method to retrieve a global variable from two separate PHP files?

Within file1.php, there is a variable: global $name; $name = ""; In the same directory, within file2.php, there is: <label> <span>Username:</span> <input id="name" type="text" name="username" value ="<?php echo $GLOBALS[& ...

Why are my multiple data-targets not functioning correctly in Bootstrap tabs?

When I attempted to create a navigation bar using Bootstrap 4 that toggles two divs when clicked on a nav-item, I discovered that you can include multiple #contents when using data-target. <a data-target="#tab-content-2, #cmcAGVL"> <nav> & ...

I will only make my website public once I have tested it thoroughly in a local environment

I was in the process of developing a website using HTML and testing it locally with Wampserver. However, I encountered an issue where clicking on a link that is supposed to redirect locally triggers the opening of another window for advertising or spam. ...

sending an array from JavaScript to a Django view

Currently, I am working with django and have a search results page that requires filtering by category using ajax (jquery) requests. The filter bar is located on the side of the page, and once a user selects specific categories and hits submit, the corresp ...

Unable to set the value of an HTML date field using Selenium on mobile devices

I am facing a challenge in setting the value of a date field on an HTML page using Selenium. The date field on the page is structured like this: <input aria-invalid="false" id="datepicker-date-input" type="date" min="2 ...