Comma between numbers script - javascript

I have tried endless solutions that I have found for this on these forums and none that I have found work or I am simply putting it in the wrong place. I am trying to force commas for thousand and millions places. Any suggestions and placement would be appreciated.
Thank you.
jQuery(window).scroll(startCounter);
function startCounter() {
var hT = jQuery('.counter').offset().top,
hH = jQuery('.counter').outerHeight(),
wH = jQuery(window).height();
if (jQuery(window).scrollTop() > hT+hH-wH) {
jQuery(window).off("scroll", startCounter);
jQuery('.counter').each(function () {
var $this = jQuery(this);
jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
duration: 4000,
easing: 'swing',
step: function () {
$this.text(Math.ceil(this.Counter));
}
});
});
}
}

Assuming you would want to comma seperate values by hunders,thousands,millions,...
You may do:
let num = 9876543210;
console.log(num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
// or
console.log((num).toLocaleString());
// or
console.log(new Intl.NumberFormat('en-US', {}).format(num));

Related

How do I add commas to this Javascript counter?

I am a beginner with JS and have no idea how to pull it off here. Idea is to have commas in the numbers to make it easier to read while counting up and also the final static result should have commas.
Eg: "10,000"
var a = 0;
$(window).scroll(function() {
var oTop = $('#counter').offset().top - window.innerHeight;
if (a == 0 && $(window).scrollTop() > oTop) {
$('.counter-value').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 2000,
easing: 'swing',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}
});
});
a = 1;
}
});
Best way is to use the built-in Intl object. More info here.
const number = 123456;
const formattedNumber = new Intl.NumberFormat('en-us').format(number);
console.log({ formattedNumber }); // 123,456

How to convert jQuery animate function to pure JS

I have this simple jquery logic, How would I convert that into pure javascript?
Besides I have to use this code in React with Typescript.
I have no clue where to start unfortunately. Any help would be extremely appreciated.
$('.counting').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({ countNum: $this.text()}).animate({
countNum: countTo
},
{
duration: 3000,
easing:'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}
});
});
I've converted that until start animate function..
let counting = document.querySelectorAll(".counting");
let countingArray = Array.prototype.slice.call(counting);
countingArray.forEach((el) => {
let countTo = el.getAttribute("data-count");
//start animate...
I referred this code in https://codepen.io/shvvffle/pen/JRALqG
An animation function for you:
function animate(render, from, to, duration, timeFx) {
let startTime = performance.now();
requestAnimationFrame(function step(time) {
let pTime = (time - startTime) / duration;
if (pTime > 1) pTime = 1;
render(from + (to - from) * timeFx(pTime));
if (pTime < 1) {
requestAnimationFrame(step);
}
});
}
render is the callback function with which you expect to update new values;
from and to are the initial values and the target values of your animation;
duration is the continuance of the animation in time in miliseconds;
timeFx is the timing function from [0, 1] to [0, 1].
You may use it as:
countingArray.forEach((el) => {
let countTo = el.getAttribute("data-count");
animate(function(newValue) {
el.innerText = Math.floor(newValue);
}, 0, countTo, 3000, x => x);
});

updating the online counter without reloading the page

Help me please. I have a script on my site that shows (online player counter on the server in GTA), when the page loads, it starts from zero to the number of players on the site. [counter code][1]
[1]: https://i.stack.imgur.com/5gkkX.jpg
var updateInterval = 700;
_timer = setInterval(updatePlayerCount, updateInterval);
function ShowCounter() {
clearInterval(_timer);
$('#online').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now));
}
});
});
}
function updatePlayerCount() {
var ip = "rage2.grand-rp.su:22005";
$.getJSON('https://cdn.rage.mp/master', function(masterlist) {
if(masterlist[ip] != undefined){
document.getElementById('online').innerHTML = masterlist[ip].players;
ShowCounter();
}
});
}
I have a _timer, it should update the numbers without reloading the page, but somehow it doesn't work. How to fix it? I posted this on jsfiddle https://jsfiddle.net/kg8uap9d/8/
Instead of setInteval, use setTimeout
var updateInterval = 5000;
_timer = setTimeout(updatePlayerCount, updateInterval);
function updatePlayerCount() {
var ip = "rage2.grand-rp.su:22005";
$.getJSON('https://cdn.rage.mp/master', function(masterlist) {
if(masterlist[ip] != undefined){
document.getElementById('online').innerHTML = masterlist[ip].players;
ShowCounter();
_timer = setTimeout(updatePlayerCount, updateInterval);
}
});
}

How can I change number format to decimals in JS

I have this counter and I need it to be in decimals (instead of having 150000000 I'd like to have 150.000.000,00 or at least 150.000.000).
I tried replace this:
step: function() {
$this.text(Math.floor(this.countNum));
}
with this:
formatter: function (value, options) {
return value.toFixed(options.decimals);
}
but it didn't work. What can I do?
These are parts of my js and html interested by this:
var a = 0;
$(window).scroll(function() {
var oTop = $('#counter').offset().top - window.outerHeight/2;
if (a == 0 && $(window).scrollTop() > oTop) {
euro.className = "testo one column hide"
$('.counter-value').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 2000,
easing: 'swing',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}
});
});
a = 1;
} else {
euro.className = "testo one column show"
}
});
<div id="counter" class="two columns counter-value" data-count="150000000">
</div>
toFixed is a good method, but it will only take care of the decimals at the end. To accomplish what you are describing you may want to use number.toLocaleString(). So your formatter would look like:
formatter: function(value, options) {
return value.toLocaleString(options);
}
You can check out the toLocaleString options in the MDN docs below:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
Hope that helps!

Adding linear easing to animation

The red box increases in height from 0 to its full height, but it does it with swing easing. I can't work out how I can make it linear.
I've tried this, and a few other things, but I can't get it to work:
$("#movement").animate({"height": open_height}, {duration: slideDuration }, {easing: linear});
Full script:
var sliderHeight = "0";
var initialDelay = 0;
var slideDuration = 2500;
$(document).ready(function(){
$('#movement').show();
$('#movement').each(function () {
var current = $(this);
current.attr("box_h", current.height());
});
$("#movement").css("height", sliderHeight);
var delay = function() { sliderOpen(); };
  setTimeout(delay, initialDelay);
  });
function sliderOpen()
{
var open_height = $("#movement").attr("box_h") + "px";
$("#movement").animate({"height": open_height}, {duration: slideDuration });
}
JS Fiddle:
http://jsfiddle.net/vs6yejag/
You didn't add linear in the demo, and it has to be given as string or it will be considered undefined:
var open_height = $("#movement").attr("box_h") + "px";
$("#movement").animate({"height": open_height},
{duration: slideDuration, easing: "linear" });
Updated fiddle
See .animate( properties, options )
easing (default: swing)
Type: String
A string indicating which easing function to use for the transition.
Try easing:"linear" ; where "linear" is String , in quotes
jsfiddle http://jsfiddle.net/vs6yejag/3/

Categories

Resources