jQuery Counter Effect encountering isNaN error when trying to display a number retrieved from a get API object

I am looking to display the numerical data retrieved from an API using JSON. I want to incorporate a counter effect that displays "isNaN" if necessary. The API URL returns an object with the total number saved in data.data. Can anyone assist me with achieving this?

<p class="Count member-count" style="color:#BA1823; font-size: 40px;">
                <script>
                    $.getJSON('https://url.com/cmp/server/api/get-total-member', function(data) {
                        var text = `${data.data}<br>`
                        $(".member-count").html(text);
                    });
                </script>
            </p>
            <script>
                $('.Count').each(function () {
                  var $this = $(this);
                  jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
                    duration: 1000,
                    easing: 'swing',
                    step: function () {
                      $this.text(Math.ceil(this.Counter));
                    }
                  });
                });
            </script>

Answer №1

One issue arises due to the asynchronous nature of the AJAX call. As a result, the each() loop that contains the animation logic executes before the request finishes, and the p element remains empty.

To resolve this issue, move the each() call inside the AJAX callback:

<p class="Count member-count"></p>
$.getJSON('https://url.com/cmp/server/api/get-total-member', function(data) {
  $(".member-count").html(`${data.data}<br>`);

  $('.Count').each(function() {
    var $this = $(this);
    jQuery({
      Counter: 0
    }).animate({
      Counter: data.data
    }, {
      duration: 1000,
      easing: 'swing',
      step: function() {
        $this.text(Math.ceil(this.Counter));
      }
    });
  });
});
.member-count {
  color: #BA1823;
  font-size: 40px;
}

Additionally, avoid placing <script> tags within the HTML structure. Instead, include them in the <head> section or just before the closing </body> tag. Similarly, refrain from embedding CSS rules in inline style attributes; it's better to use external .css files. You can view a corrected version of the HTML and JS in this jsFiddle.

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

Send the user back to the previous page once authentication is complete

I am integrating Google authentication through Passport in my web application and I am facing an issue with redirecting the user back to the original page they requested after a successful sign-in. It seems like the use of location.reload() might be causin ...

I'm having trouble with Gutters GX and GY not functioning properly in Bootstrap, HTML, and CSS

I attempted to incorporate gutters into my Bootstrap grid layout, however, they are not showing up as expected. I am following the guidelines provided on the Bootstrap documentation, but for some reason, the gutters are not appearing. <!DOCTYPE html> ...

Embellishing Bootstrap with a splash of color class

After exploring Bootstrap, I've noticed the limited number of "color classes" available (primary, success, danger etc.). Is there a simple way to add more classes similar to those? For instance, the "primary" class can be used across various elements ...

Tips for troubleshooting the error message "is not a function" in a React application

Hi there, I'm currently delving into learning React and have encountered an issue that says: (TypeError: newsData.map is not a function) in my browser when running my code. Oddly enough, Visual Studio Code doesn't flag any errors, only Chrome doe ...

Executing code upon the completion of jquery's slideUp() function

Is there a method to trigger the execution of html() only after the completion of slideUp()? <p class="test">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent tortor elit</p> $(".test").slideUp().html(""); I attempted using ...

Looking for a streamlined process to manage the development and publication of multiple versions of the React module using the "yarn/npm link" workflow

Currently, I am in the process of developing and releasing a module on npm that relies on the React library. As part of my workflow, I am utilizing yarn along with yarn link. The module has been created within a larger parent project, but now I am looking ...

Tips for setting up OpenLayers demonstrations on a personal server?

Currently, I'm working with an older version of OpenLayers (4.6.2) and find the provided examples extremely helpful for testing and reference purposes. However, the official web page with updated examples only includes the latest version. I am wonder ...

What is the process for capturing a screenshot of a specific DOM element using Intern JS?

I'm currently utilizing intern.js for testing a web application. It allows me to run tests and generate screenshots in case of failures. My goal is to capture a screenshot of a specific element for conducting CSS regression testing with tools like res ...

Erase a chat for only one user within a messaging application

Currently, I am in the process of building a chat application using nodejs and mongodb. In order to structure my database properly, I have created two models: conversation and messages. Message.js conversationId: { //conversationID }, body: ...

What is the best way to ensure an observable has been updated before proceeding with additional code execution?

Is an observable the best choice for providing live updates of a variable's value to another class? I have a loop in my service class that looks like this: elements.forEach(element => { doStuff(); this.numberSubject.next(valueFromDoStuff); }) ...

Guide to making a toggle button with a Light/Dark mode functionality

I have implemented a light/dark toggle button and now I want to integrate the functionality for switching between light and dark themes on my webpage. The switch should toggle the theme between dark and light modes when clicked. Some basic styling has been ...

The React Navbar fails to appear when using React JS

I am currently in the process of creating a single-page website. I have incorporated react-bootstrap for the navigation bar, but I am facing an issue where it is not rendering on the page. Despite not encountering any errors, the page remains blank. Below ...

Validate if a variable is present in a JSON object

I am currently facing an issue that I cannot solve on my own, so I would greatly appreciate any assistance. The problem I am encountering involves a dynamic cart that is populated with JSON data. The shipping costs in the cart are also filled from the sam ...

AngularJS' $rootScope is experiencing issues with creating internal variables

My app utilizes $rootScope.requestObj to store key-value pairs representing filters. Throughout the entire application, $rootScope.requestObj is considered a singleton and behaves as expected. However, when I call an external API, I have a service that t ...

What is the proper way to include an attribute to every individual object within an array?

Here is the structure of my array: "taxDetails": [ { "taxType": "Flat Service Charge", "taxAmount": 0 }, { "taxTypeId": "1", "taxType": "Service Tax", "validFrm": "2016-01-18", "validTo": "2020-02-27", "taxPrctgSbt": 200, "taxPrctg": 14.5, ...

Is it possible to disable the pointer event on the parent element only in CSS

Here's the structure I'm working with: <div class='offline'>some text <button class='delete'>Delete</button></div> I want to disable the div using pointer-events: none, but still keep the button activ ...

What is the most efficient way to refresh a React component when a global variable is updated?

I've built a React component called GameData that displays details of a soccer game when it is clicked on in a table. The information in the table is updated by another component, which changes a global variable that GameData relies on to show data. S ...

Create a toggle effect using attribute selectors in CSS and JavaScript

I am looking to switch the "fill: #000;" from the CSS property "svg [id^='_']". Usually, I would use a method like this, but it seems that I can't do so because "svg [id^='_']" is not an element, correct? pub.toggleClass = functi ...

What is the best way to deselect the first radio button while selecting the second one, and vice versa, when there are two separate radio groups?

I am looking to achieve a functionality where if the first radio button is selected, I should receive the value true and the second radio button should be unselected with the value false. Similarly, if the second radio button is selected, I should receive ...

Troubleshooting: Jquery show effects not functioning as expected

Currently, I am facing an issue where I am attempting to display a fixed div using the show function of jQuery. Although the show function itself is working properly, when I try to include an effect from jQuery UI, it does not seem to work as expected. Bot ...