Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a percentage counter in jQuery?

I tried to create a percentage counter but it doesn't do something that I need. It just shows 100%. However I need to show all 0 to 100% step by step! How should I change it?

setInterval(function per(p = 0) {
  for (p = 1; p <= 100; p++) {
    $(".percentage").text(p + "%");
  }
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="percentage"></p>
like image 229
S. Ensiye Kiyamousavi Avatar asked Jun 21 '17 10:06

S. Ensiye Kiyamousavi


People also ask

How to create a percentage ring using jQuery?

percircle.js is a lightweight jQuery plugin used to create a pure CSS circle / ring to represent percentage data using CSS3 transforms and a little JavaScript. Great for creating progress bars or loading indicators for your web application. 1. Include jQuery library together with the jQuery percircle's JavaScript and style sheet on the web page.

How to calculate percent in JavaScript?

Let’s start with an easy example. Take a look at the following JavaScript code: //Our number. var number = 120; //The percent that we want to get. //i.e. We want to get 50% of 120. var percentToGet = 50; //Calculate the percent. var percent = (percentToGet / 100) * number; //Alert it out for demonstration purposes.

How do I use a counter on my website?

The way it works is that each time an element is clicked, the counter (which starts at 0) goes up by one. The counter can be applied to the clicking of any particular elements or multiple elements, and you can choose whether or not to display it somewhere on your page or site, or log the counter to the console, or use the counter in a function.

How to create a percentage circle in HTML?

Create the html structure for the percentage circle. class="big": big percentage circle. "small" = small size. Empty = medium size 3. Activate the plugin and done.


1 Answers

The issue is because the for loop runs in a fraction of a second, regardless of the setInterval.

To fix this you could change your logic to use recursion and then delay each iteration by 1 second, like this:

function updatePercentage(p) {
  p = p || 0;
  $(".percentage").text(p + "%");
  if (p < 100) {
    setTimeout(function() {
      updatePercentage(++p);
    }, 1000);
  }
}

updatePercentage();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="percentage"></p>
like image 65
Rory McCrossan Avatar answered Sep 23 '22 17:09

Rory McCrossan