A step-by-step guide to creating a single scroll-triggered animation

Check out my code snippet on this JSFiddle link.

const ratingcount = document.querySelectorAll('.ratingcount');
const totalratingcounter = ratingcount.length;

var stopNow = totalratingcounter

countEach()
$(window).on('scroll', function(e) {
      countEach()
})

function countEach() {
    $('.ratingcount').each(function() {
        if (showOnScreen(this) && $(this).attr('show') != 'false' && stopNow != 0) {
            console.log($(this).text())
            console.log($(this).attr('show'))
            $(this).attr('show', 'false')
            numberAnimate(this)
            stopNow = stopNow - 1;
        } else if (!showOnScreen(this)) {
            $(this).attr('show', 'true')
        }
    })
}

function showOnScreen(target) {

    if ($(window).scrollTop() + $(window).height() >= $(target).offset().top)
      return true;
    else
        return false;
}

function numberAnimate(target) {
    var $this = $(target);
    jQuery({
        Counter: 0
    }).animate({
        Counter: $this.text()
    }, {
        duration: 1000,
        easing: 'swing',
        step: function() {
            $this.text(this.Counter.toFixed(1));
        }
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
Follow my steps, Scroll down to middle
</h1>
<span class="ratingcount">5.6</span><br/>
<span class="ratingcount">5.6</span>

<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/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>

<span class="ratingcount">5.6</span><br/>
<span class="ratingcount">5.6</span>
<h1>NOW SCROLL UP AGAIN and  then scroll down 
</h1>

<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/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>

<h1>
Now see this is not working 
</h1>
<span class="ratingcount">5.6</span><br/>
<span class="ratingcount">5.6</span>

A common issue arises when using the following code:

const ratingcount = document.querySelectorAll('.ratingcount');
const totalratingcounter = ratingcount.length;

This code snippet calculates the quantity of elements with the class name ratingcount.

Furthermore, the script halts the animation after each instance has been animated based on the class count.

var stopNow = totalratingcounter

The challenge lies in how a single number can animate multiple times while others cannot due to the scroll behavior.

For example: If you scroll down to a number in the middle, it will trigger the animation. However, upon scrolling back up and down again, the middle number animates once more, whereas the bottom number does not.

Answer №1

It seems like you're looking to animate each rating counter only once, when it is first displayed on the screen. To achieve this effect, simply remove the else if() {...} block from your countEach() function, as shown below:

const ratingcount = document.querySelectorAll('.ratingcount');
const totalratingcounter = ratingcount.length;

var stopNow = totalratingcounter

countEach()
$(window).on('scroll', function(e) {
      countEach()
})

function countEach() {
    $('.ratingcount').each(function() {
        if (showOnScreen(this) && $(this).attr('show') != 'false' && stopNow != 0) {
            //console.log($(this).text())
            //console.log($(this).attr('show'))
            $(this).attr('show', 'false')
            numberAnimate(this)
            stopNow = stopNow - 1;
        }
    })
}

function showOnScreen(target) {

    if ($(window).scrollTop() + $(window).height() >= $(target).offset().top)
      return true;
    else
        return false;
}

function numberAnimate(target) {
    var $this = $(target);
    jQuery({
        Counter: 0
    }).animate({
        Counter: $this.text()
    }, {
        duration: 1000,
        easing: 'swing',
        step: function() {
            $this.text(this.Counter.toFixed(1));
        }
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
Follow my steps, Scroll down to middle
</h1>
<span class="ratingcount">5.6</span><br/>
<span class="ratingcount">5.6</span>

...

</span>

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

Having difficulty selecting an element using XPath based on its title

https://i.stack.imgur.com/Of29v.png My XPath: ((//span[text()='Number of Allowances'])/../../../following::div//table[@class='mainTable']//tr[1]//input[@data-automation-id="numericInput"]) The XPath above clearly specifies that the ai ...

Blank white screen in Three.js following the rendering of numerous objects

I have a situation where I am loading over 4350 3D objects from JSON files in my game. for (var y in game.fields) { for (var x in game.fields[y]) { switch (game.fields[y][x]) { case 'm': ...

Radio button fails to be marked as selected

Currently, I am conducting a test on , and one of the tasks involves styling Radio Buttons using JavaScript (jQuery). Despite my repeated attempts to reconstruct the code, I always encounter the same issue: although JS successfully sets the input radio but ...

Codeigniter 3 and JQuery seamless refresh: A dynamic duo

I'm currently attempting to utilize the following code: setInterval(function() { $('#myDiv').load('contentToLoad.php');}, 5000); while working with CodeIgniter. My attempt so far has been: setInterval(function() { $('.image ...

Refresh Material-Ui's Selection Options

Is there a way to properly re-render the <option> </option> inside a Material UI select component? My goal is to transfer data from one object array to another using the Material UI select feature. {transferData.map(data => ( <option ...

Difficulty encountered when trying to obtain div height automatically

For a while now, I've been attempting to dynamically determine the height of an image as the browser window is adjusted. Despite using console.log() to verify my results, I keep getting a value of 0. What could be causing this discrepancy? $(functio ...

What is the process for sending a parameter in getStaticProps within Next.js

Is there a way in NextJS to call an API when a user clicks the search button and display the relevant result? Thanks for your input! The API I'm currently utilizing is , with "Steak" referring to the specific food item of interest. In my development ...

What is the method for accessing a map that has been set in a separate component?

My current setup involves utilizing a Leaflet map with vue2leaflet. The process I follow is quite standard: I import a list of places from a REST Api in the app store (vuex) Following that, during map initialization, the markers are created using the in ...

Prevent the overlap of text by controlling the positioning of a div element

Below is a simplified version of the layout I'm working with: <div style="position: relative; width:600px;"> <p>Content with unknown length, but very lengthy</p> <div>Content with unknown height</div&g ...

Choose several files to upload, as displayed in an HTML table

I am trying to determine the number of files selected using a file selection tag that populates an HTML table with a button in each row. My goal is to identify the total count of selected files when clicking on the button in the same row and then proceed ...

Increase the line spacing within paragraphs by eliminating the extra space at the top and bottom

Trying to adjust line height in a paragraph using CSS. Here is the HTML: <div> <p>Lorem ipsum dolor sit amet, oratio doctus his an. Nisl saperet delenit ad eos, his eros solet vituperata et, has tantas nemore consetetur ne. Nam cu au ...

Saving automatic Javascript increments into a Django database

I have a JavaScript function that increments a value retrieved from my database every 3.5 seconds. However, I am now facing the challenge of saving these incremented values back to the database in real-time using Django and JavaScript. Every time I refres ...

Discover how to use jQuery to locate and substitute a class of an element

I'm currently facing a limitation on the platform I'm using, as it restricts me from making HTML changes. To work around this constraint, I have to utilize JQuery to locate and swap one div with another (or in simpler terms, find specific text in ...

Automatically updating the USD amount when changed using onchange event in JavaScript

https://i.sstatic.net/SjxRl.pngI am struggling with this code and despite looking at numerous related questions, I have not found a solution that works. Can someone please assist me? Here are the specific things I need help with: I need to automatically ...

Use the .filter() method in JavaScript to generate an array containing abbreviated strings

Can anyone provide guidance on how to abbreviate an array of strings using the filter() method? I am trying to use filter() with str.substring or another string method, but I'm not sure how to make it work properly. In this code snippet, my goal is ...

When the onClick event is triggered, Next.js will dynamically render a new

Looking to display a larger version of an image in a new div upon click? Here are four different methods I've tested: Render div on Click function zoom_img (event) { console.log(event.target); console.log(event.target['data-loaded-src&a ...

What is the process for authenticating and sending a click conversion to Google Ads using a service account and the REST API with TypeScript?

I have attempted to authenticate using this documentation and to send conversions via REST API using this REST endpoint due to the absence of a Typescript/Javascript Client Library. However, I am encountering authentication issues. Once resolved, I aim to ...

Unusual SASS results observed while utilizing extends functionality

Having issues with my SASS files: _android.scss: $width: 111px; @import 'child'; .android .child { @extend %child; } _ios.scss: $width: 999px; @import 'child'; .ios .child { @extend %child; } _child.scss: %child { wi ...

What is the best way to define a list of floating point numbers in Realm for JavaScript?

Recently, I experimented with a schema using realm-js library that included the following properties: floatArray: {type:'list', objectType:'float'} However, I encountered an error message stating "Schema validation failed ...

Saving HTML form data to a server-side text file

All. I've discovered various scripts that allow you to save form input to your local computer, such as downloading a text document with the submitted information. However, I am trying to create an HTML form that, when the 'submit' button is ...