I'm trying to output the final numeric value but formatted in the form of currency to show the currency symbol and commas. I tried integrating a conversion function that I found on here but having some trouble including it in the entire code. I'm quite new to this so please let me know where I went wrong in your comments and what's the best direction to go in.
This is the code for the counter:
function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
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: numberWithCommas.call($this.text())
}).animate({
countNum: countTo
}, {
duration: 2000,
easing: 'swing',
step: function () {
$this.text(Math.floor(this.countNum));
},
complete: function () {
$this.text(this.countNum);
}
});
});
a = 1;
}
});
.counter-value {
font-size: 60px;
line-height: 2em;
text-align: center;
padding: 17px 0;
}
.counter-value:after {
content: attr(data-desc);
display: block;
text-transform: uppercase;
font-size: 14px;
line-height: 1.2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="counter">
<div class="sqs-col sqs-col-4 counter-value" data-count="2500" data-desc="Happy Clients">0</div>
<div class="sqs-col sqs-col-4 counter-value" data-count="1000" data-desc="Projects Completed">0</div>
</div>
as Kawaljit Singh suggest, or simply use toLocaleString()
const nForm = new Intl.NumberFormat('en-EN')
, nFormUSD = new Intl.NumberFormat('en-EN',{style: "currency", currency: "USD"})
, nFormFix2 = v => nForm.format(v.toFixed(2))
;
let ValueX = 1234567.123456;
console.log('Intl.NumberFormat =>', nForm.format(ValueX))
console.log('Intl.NumberFormat USD =>', nFormUSD.format(ValueX))
console.log('Intl.NumberFormat in nFormFix2', nFormFix2(ValueX))
console.log( "x.toLocaleString('en-EN')", ValueX.toLocaleString('en-EN'))
.as-console-wrapper { max-height: 100% !important; top: 0; }
doc :
Country Currency Codes :
-> https://www.iban.com/currency-codes
Intl.NumberFormat.prototype.format() :
-> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat/format
Number.prototype.toLocaleString() :
-> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
Related
var container = document.querySelector(".container");
var bar = document.querySelector(".bar");
var barL = document.getElementsByClassName("barLayer");
var value = document.getElementsByClassName("value");
var compare = document.getElementsByClassName("compare"); // array vallue to show than code can't get the correct result of that bar's height
var pixelStep = 4; // cooficient to expand bar height. if val=100 => bar.height = 400px
var barNum = 12; // number of bars
var spaceBetween = 100; // space between bars
var intervalTime = 10; // ms reading transition changes
var delayTime = 50; // ms after drawing previous bar.
const data = [
{ brand : "SAMSUNG", val : 40, color : "#c00"},
{ brand : "APPLE", val : 46, color : "#0c0"},
{ brand : "HUAWEI", val : 43, color : "#f84"},
{ brand : "ASUS", val : 71, color : "#248"},
{ brand : "XIAOMI", val : 53, color : "#0cc"},
{ brand : "OPPO", val : 100, color : "#cc0"},
{ brand : "VIVO", val : 66, color : "#c0c"},
{ brand : "MOTOROLA", val : 86, color : "#ccc"},
{ brand : "LENOVO", val : 61, color : "#c40"},
{ brand : "LG", val : 93, color : "#333"},
{ brand : "NOKIA", val : 83, color : "#088"},
{ brand : "OTHERS", val : 51, color : "#06c"} ];
sortFunction(data, "val"); //sort Array
clone(bar, container); // clone bar for (barNum-1) times
for(let i = 0; i < data.length; i++){ barL[i].style.backgroundColor = data[i].color; } // colorize every bar with corresponding array color value
//---------------
var myInterval = [];
function anim(j){ // draw bars one after the other in sequence
const computedStyleObj = getComputedStyle(barL[j]);
value[j].textContent = Math.round(parseInt(computedStyleObj.height)/pixelStep) + "K";
compare[j].textContent = data[j].val;
barL[j].style.height = value[j].style.bottom = (data[j].val * pixelStep) + "px" //transiton value of height
//console.log("j : ", data[j].val + " - " + parseInt(computedStyleObj.height));
barL[j].addEventListener("transitionEnd", () =>{clearInterval(myInterval[j]);}); // when transition ends, clear interval
barL[j].addEventListener("webkitTransitionEnd", () =>{clearInterval(myInterval[j]);});
}
for (let i = 0; i < data.length; i++) {
setTimeout(function() {
myInterval[i] = setInterval(function() {anim(i);}, intervalTime); // after delayTime ms start the next bar animation
}, i * delayTime);
}
//----------------
function clone(item, container) { // clone an item in a container function
for(let i = 0; i < barNum-1 ; i++){
var cln = item.cloneNode(true);
container.appendChild(cln);
cln.style.left = ((i+1) * spaceBetween ) + "px";
}
}
function sortFunction(arr, key) { // sort an array of objects by given key
arr.sort(function(a, b){
let x = a[key];
let y = b[key];
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});
data.reverse(); // reverse for descending array
}
:root {
--barWidth : 80px;
--color : #aaa;
--contentWidth : 1200px;
}
* {
margin : 0;
padding : 0;
box-sizing : border-box;
}
body {
width : 100%;
display : flex;
align-content : center;
justify-content : center;
flex-direction : column;
background : var(--color);
font-family : 'Roboto Mono', monospace;
}
.container {
position : relative;
width : var(--contentWidth);
height : 500px;
border : 1px solid #0005;
background : #fff4;
margin : 10px auto;
}
.bar {
position : absolute;
width : var(--barWidth);
margin : 10px;
display : inline-block;
border : 0px solid #0005;
bottom : 0px;
}
.barLayer {
position : absolute;
width : var(--barWidth);;
height : 0px;
bottom : 0;
border : 0px solid #0005;
}
.value, .compare {
position : absolute;
width : var(--barWidth);
height : calc(var(--barWidth)/2);
bottom : 0px;
font-size : calc(var(--barWidth)/4);
text-align : center;
border : 0px solid #fff;
line-height : calc(var(--barWidth)/2);
}
.barLayer, .value {
transition : all 1s linear;
}
<div class="container">
<div class="bar">
<div class="barLayer"></div>
<div class="value"></div>
<div class="compare"></div>
</div>
</div>
I want to clear "interval" after transition end (drawing bar with transition animation) not to busy CPU in vain, but I can't get the correct height value.
You can see the result using snipped link below.
Top is wrong value, bottom is the data from array. I tried some arithmetic methods, but want to use "transitionend" eventListener. Thanks! :)
TL;DR: for animation stuff, use requestAnimationFrame
Usually for animation related things, we prefer using requestAnimationFrame than intervals or timeout. You can think of requestAnimationFrame as a setTimeout that will trigger on the next frame. So I'm proposing this as a replacement for your setInterval.
As for the measure of "how far along is this bar" to animate the numbers, I think you'll get a good enough approximation by just watching how much time has elapsed and how long the transition is supposed to last. This will not be precise by any means, but measuring the elements with getComputedStyle or getBoundingClientRect on every frame would be a disaster for fluidity. So this is why I'm using timestamps in watchAnimation.
And for the rest, I didn't change much. Just re-wrote your code because (sorry but) it was a bit of a mess, and way too many things that didn't have anything to do with the problem at hand.
const container = document.querySelector('.container')
const bar = document.querySelector('.bar')
const values = [100, 80, 63, 20]
const DURATION = 1000 //ms
values.forEach((value, i) => {
initItems(value, i)
staggeredStart(value, i)
watchAnimation(value, i)
})
function initItems(value, i) {
let item = container.children.item(i)
if(!item) {
item = bar.cloneNode(true)
container.appendChild(item)
}
// other things to initialize items
}
function staggeredStart(value, i) {
const item = container.children.item(i)
setTimeout(() => {
item.classList.add('animate')
item.addEventListener('transitionend', () => {
item.classList.remove('animate')
}, {once: true, passive: true})
item.style.setProperty('--value', `${100 - value}%`)
}, i * 50)
}
function watchAnimation(value, i) {
const item = container.children.item(i)
const span = item.querySelector('.value')
span.textContent = '0'
let requestAnimationFrameId
let startTime
function onStart(event) {
startTime = event.timeStamp
onFrame()
}
function onEnd() {
cancelAnimationFrame(requestAnimationFrameId)
span.textContent = value
}
function onFrame() {
requestAnimationFrameId = requestAnimationFrame((time) => {
const delta = time - startTime
const ratio = Math.min(Math.max(0, delta / DURATION), 1)
span.textContent = Math.round(value * ratio)
onFrame()
})
}
item.addEventListener('transitionstart', onStart, {once: true, passive: true})
item.addEventListener('transitionend', onEnd, {once: true, passive: true})
}
* {
box-sizing: border-box;
}
.container {
height: 500px;
border: 1px solid #0005;
overflow: hidden;
display: flex;
--bar-width: 80px;
--space-for-value: 40px;
}
.bar {
--value: 100%;
position: relative;
width: var(--bar-width);
height: calc(100% - var(--space-for-value));
top: var(--space-for-value);
transform: translateY(var(--value));
}
.bar:not(:first-child) {
margin-left: 20px;
}
.bar.animate {
transition: transform 1s linear;
}
.layer {
position: absolute;
width: 100%;
height: 100%;
bottom: 0;
background: red;
}
.value {
position: absolute;
width: 100%;
height: var(--space-for-value);
bottom: 100%;
text-align: center;
line-height: var(--space-for-value);
}
<div class="container">
<div class="bar">
<div class="layer"></div>
<div class="value"></div>
</div>
</div>
Trying to develop my website and got a problem with a jQuery plugin.
After searching through google 'till the page 9 of the the search, I've found an working JavaScript plugin that simply counts up ( I'll let a link as an exemple, it's as you scroll down a site and it displays a count up effect from 0 to a desired number in a desired amount of time).
It works amazing - and not gonna lie, it's the the only functional one I found in 8 pages of internet- but, if i try to copy+paste the plugin on the site( like, to double it) it blows the first plugin and they interfere with each other ( no matter what number i set the second one to count till, it will count as the first one). Basically, they blow each other up.
Link: https://jsfiddle.net/YWn9t/
My question:
Why is this thing happening? My hand-errors or?
As far as my experience with coding takes me, i know each plugin has some kind of name, like to indentify which is which. May this be the base of the error? Like, i have to change the name of the second? And if yes, which line/ lines should i modify?
Do you have this kind of plugin?
L.E.: Forgot to mention. I use a sitebuilder: WebWave so it must have a css code, html and jv code.
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
jQuery(function($) {
$('.timer').countTo({
from: 50,
to: 2500,
speed: 5000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
.timer {
width: 200px;
margin: 20px auto;
text-align: center;
display: block;
font-size: 20px
}
#help {
width: 500px;
margin: 20px auto;
text-align: center;
display: block;
font-size: 14px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="timer"></span>
<hr/>
<span id="help">From: 50 - To: 2500 / Over 5000 Milli-Seconds</span>
Works for me when I use unique IDs
Remove the display:block to align horizontally
For example
(function($) {
$.fn.countTo = function(options) {
options = $.extend({}, $.fn.countTo.defaults, options || {});
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0,
to: 100,
speed: 1000,
refreshInterval: 100,
decimals: 0,
onUpdate: null,
onComplete: null,
};
})(jQuery);
jQuery(function($) {
$('#timer1').countTo({
from: 50,
to: 2500,
speed: 5000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
$('#timer2').countTo({
from: 1550,
to: 4500,
speed: 5000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
.timer {
width: 200px;
margin: 20px auto;
text-align: center;
font-size: 20px;
padding: 50px;
}
#help {
width: 500px;
margin: 20px auto;
text-align: center;
display: block;
font-size: 14px
}
#container {
text-align: center
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<span class="timer" id="timer1"></span>
<span class="timer" id="timer2"></span>
</div>
<hr/>
<span id="help">From: 50 - To: 2500 / Over 5000 Milli-Seconds</span>
Please I need I help on how to implement something like this responsively using bootstrap
html code for is displayed below
<div class="wrapper">
<div class="container">
<div class="special">
<div id="counter">
<div id="shading"></div>
</div>
</div>
</div>
please below is the css file for the above html code
.special
{
position: relative;
width: 840px;
height: 247px;
background-image: url('https://www.jqueryscript.net/demo/Colorful-Countdown-Timer/images/special_offer_bg.png');
background-position: -10px 74px;
background-repeat: no-repeat;
}
#counter
{
position: absolute;
top: 135px;
left: 279px;
z-index: 4000;
}
.digit-separator
{
position: relative;
float: left;
width: 17px;
height: 44px;
overflow: hidden;
background-image: url('https://www.jqueryscript.net/demo/Colorful-Countdown-Timer/images/digit_separator.png');
background-repeat: no-repeat;
background-position: 0px 0px;
}
.digit
{
background-image: url('https://www.jqueryscript.net/demo/Colorful-Countdown-Timer/images/digits.png');
}
#shading
{
background-image: url('https://www.jqueryscript.net/demo/Colorful-Countdown-Timer/images/sprites.png');
background-position: 0px -396px;
background-repeat: repeat-x;
float: left;
height: 44px;
position: absolute;
width: 291px;
z-index: 4100;
top: 0;
left: 0;
}
please this is the JavaScript code for the above html code
function C3Counter(id, opt) {
this.options = {
stepTime: 60, // not used
format: "dd:hh:mm:ss", // not used
startTime: "01:04:40:59",
digitImages: 1,
digitWidth: 30,
digitHeight: 44,
digitSlide : true,
digitSlideTime : 200,
digitImageHeight : 484,
digitAnimationHeight : 44,
timerEnd: function(){},
image: "digits.png",
updateInterval : 1000
};
var s;
if (typeof opt != "undefined") {
for (s in this.options) {
if (typeof opt[s] != "undefined") {
this.options[s] = opt[s];
}
}
}
if (String(options.startTime).indexOf(":") == -1) {
options.tempStartTime = options.startTime;
} else {
//TODO - does not convert time with : to seconds to count
var td = new Date(options.startTime);
}
this.pad2 = function(number) {
return (number < 10 ? '0' : '') + number;
}
var timer = setInterval( "this.updateCounter()", options.updateInterval);
var startTime = new Date().getTime();
var secNo = 0;
var timerSingle = new Array();
var dc = 0;
var digits = new Array();
var d = new Date();
var lastTime = d.getTime();
this.calculateTime = function() {
var tempTime = options.tempStartTime;
if (String(options.tempStartTime).indexOf(":") == -1) {
var seconds=Math.round(options.tempStartTime % 60);
options.tempStartTime=Math.floor(options.tempStartTime/60);
var minutes=Math.round(options.tempStartTime % 60);
options.tempStartTime=Math.floor(options.tempStartTime/60);
var hours=Math.round(options.tempStartTime % 24);
options.tempStartTime=Math.floor(options.tempStartTime/24);
var days=Math.round(options.tempStartTime);
options.timeStr = this.pad2(days)+this.pad2(hours)+this.pad2(minutes)+this.pad2(seconds);
}
var currTime = new Date().getTime();
var diff = currTime - startTime;
options.tempStartTime = options.startTime - Math.round(diff/1000);
}
this.calculateTime();
for (dc=0; dc<8; dc++) {
digits[dc] = { digit: this.options.timeStr.charAt(dc)};
$("#"+id).append("<div id='digit"+dc+"' style='position:relative;float:left;width:"+this.options.digitWidth+"px;height:"+this.options.digitHeight+"px;overflow:hidden;'><div class='digit' id='digit-bg"+dc+"' style='position:absolute; top:-"+digits[dc].digit*this.options.digitAnimationHeight+"px; width:"+this.options.digitWidth+"px; height:"+this.options.digitImageHeight+"px; '></div></div>");
if (dc % 2 == 1 && dc < 6) {
$("#"+id).append("<div class='digit-separator' style='float:left;'></div>");
}
}
$("#"+id).append("<div style='clear:both'></div>");
this.animateDigits = function() {
for (var dc=0; dc<8; dc++) {
digits[dc].digitNext = Number(this.options.timeStr.charAt(dc));
digits[dc].digitNext = (digits[dc].digitNext + 10)%10;
var no = dc;
if (digits[no].digit == 0) $("#digit-bg"+no).css("top", -this.options.digitImageHeight+this.options.digitHeight + "px");
if (digits[no].digit != digits[no].digitNext) {
$("#digit-bg"+no).animate( { "top" : -digits[no].digitNext*options.digitHeight+"px"}, options.digitSlideTime);
digits[no].digit = digits[no].digitNext;
}
}
var end = this.checkEnd();
}
this.checkEnd = function() {
for (var i = 0; i < digits.length; i++) {
if (digits[i].digit != 0) {
return false;
}
}
clearInterval(timer);
this.options.timerEnd();
return true;
}
this.updateCounter = function() {
d = new Date();
if ((d.getTime() - lastTime) < (options.updateInterval - 50)) {
return;
}
lastTime = d.getTime();
this.calculateTime();
this.animateDigits();
}
}
C3Counter("counter", { startTime :16100 });
Note* you need to use Bootstrap v3.3.4 or higher and jQuery v2.1.3 or higher
Note* This doesnt look like the exact example you linked to. Its not posible to achieve that with default boostrap library.
html:
<div class="wrapper">
<div class="special">
<span id="clock"></span>
</div>
</div>
js:
$('#clock').countdown('2020/10/10', function(event) {
$(this).html(event.strftime('%D days %H:%M:%S'));
});
css:
.wrapper
{
width: 100%;
height: auto;
background-color: #dc403b;
}
.special
{
width:100%;
background-image: url('https://www.jqueryscript.net/demo/Colorful-Countdown-Timer/images/special_offer_bg.png');
background-position: cover;
background-repeat: no-repeat;
text-align: center;
padding: 50px 0;
font-size: 18px;
}
For teaching myself javascript (and for getting/giving more insight in the field of astronomy :) ), I am setting up a page that displays relative positions of sun and moon.
Right now, the speed of the sun and moon movement is still fixed, but I would really like to make this dynamically user-definable via an input field. So, the initial speed is '30', and a user can speed this up or slow this down. Obviously, the ratio between sun and moon must stay fixed. I tried a lot of things (see some relics in the code, but I can't get it to work.
Anyone with more experience with javascript can assist me in doing this? Also, I notice CPU usage gets very high during this animation. Are there simple steps in making this script more efficient?
var dagen = 0;
function speed($this){
var speedSetting = $this.value;
//alert(speedSetting);
//return per;
}
function periode(bolletje, multiplier=30){
if (bolletje == 'zon'){var per = (multiplier*24/2);}
if (bolletje == 'maan'){var per = (multiplier*24*29.5/2);}
return per;
}
function step(delta) {
elem.style.height = 100*delta + '%'
}
function animate(opts) {
var start = new Date
var id = setInterval(function() {
var timePassed = new Date - start
var progress = timePassed / opts.duration
if (progress > 1) progress = 1
var delta = opts.delta(progress)
opts.step(delta)
if (progress == 1) {
clearInterval(id)
}
}, opts.delay || 10)
}
function terugweg(element, delta, duration) {
var to = -300;
var bolletje = element.getAttribute('id');
per = periode(bolletje);
document.getElementById(bolletje).style.background='transparent';
animate({
delay: 0,
duration: duration || per,
//1 sec by default
delta: delta,
step: function(delta) {
element.style.left = ((to*delta)+300) + "px"
}
});
if(bolletje == 'zon'){
dagen ++;
}
bolletje = element;
document.getElementById('dagen').innerHTML = dagen;
//setInterval(function (element) {
setTimeout(function (element) {
move(bolletje, function(p) {return p})
}, per);
}
function move(element, delta, duration) {
var to = 300;
var bolletje = element.getAttribute('id');
per = periode(bolletje);
document.getElementById(bolletje).style.background='yellow';
animate({
delay: 0,
duration: duration || per,
//1 sec by default
delta: delta,
step: function(delta) {
element.style.left = to*delta + "px"
}
});
bolletje = element;
//setInterval(function (element) {
setTimeout(function (element) {
terugweg(bolletje, function(p) {return p})
}, per);
}
hr{clear: both;}
form{display: block;}
form label{width: 300px; float: left; clear: both;}
form input{float: right;}
.aarde{width: 300px; height: 300px; border-radius: 150px; background: url('https://domain.com/img/aarde.png');}
#zon{width: 40px; height: 40px; background: yellow; border: 2px solid yellow; border-radius: 20px; position: relative; margin-left: -20px; top: 120px;}
#maan{width: 30px; height: 30px; background: yellow; border: 2px solid yellow; border-radius: 16px; position: relative; margin-left: -15px; top: 115px;}
<form>
<div onclick="move(this.children[0], function(p) {return p}), move(this.children[1], function(p) {return p})" class="aarde">
<div id="zon"></div>
<div id="maan"></div>
</div>
Dagen: <span id="dagen">0</span>
</form>
<form>
<label><input id="snelheid" type="range" min="10" max="300" value="30" oninput="speed(this)">Snelheid: <span id="snelheidDisplay">30</span></label>
</form>
First, change onlick to oninput in speed input tag.
<input id="snelheid" type="number" value="30" oninput="speed(this)">
And in your speed() function set multiplier = $this.value. multiplier should be global:
var multiplier = 30;
function speed($this){
console.log($this.value);
multiplier = $this.value;
//alert(speedSetting);
//return per;
}
function periode(bolletje){
if (bolletje == 'zon'){var per = (multiplier*24/2);}
if (bolletje == 'maan'){var per = (multiplier*24*29.5/2);}
return per;
}
Here is an example:
https://jsfiddle.net/do4n9L03/2/
Note: multiplier is not speed, it is delay. If you increase it it become slower
I've looked at some similar questions, but couldn't find a solution that worked for me. I have some counters on my page, and I want them to start counting only when I reach that div in my view. any ideas? Thanks.
Here's my code...:
// JS plugin + code for counter up
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
jQuery(function($) {
var div_header = $('#counters').offset().top;
var window_top = $(window).scrollTop();
//alert(window_top);
//alert(div_header);
if(div_header == window_top) {
alert('success');
}
$('.hours span').countTo({
from: 50,
to: 1400,
speed: 2000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
$('.exposure span.numbers').countTo({
from: 50,
to: 300,
speed: 2000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
$('.types span').countTo({
from: 0,
to: 10,
speed: 2000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
#counters {
font-family: 'opensans', sans-serif;
color: white;
font-size: 5em;
display: block;
padding: 4%;
text-align: center;
font-weight: 100;
background-color: #222020;
}
#counters div {
width: 30%;
display: inline-block;
vertical-align: top;
}
#counters span, .exposure:after {
font-size: 0.8em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<section id="counters">
<div class="hours">
<span></span>
<h3>header1</h3>
</div>
<div class="exposure">
<span class="numbers"></span><span>%</span>
<h3>header2</h3>
</div>
<div class="types">
<span></span>
<h3>header3</h3>
</div>
</section>