-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathpurecounter.js
398 lines (359 loc) · 16.5 KB
/
purecounter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
export default class PureCounter {
constructor(options = {}) {
/** Default configurations */
this.defaults = {
start: 0, // Starting number [uint]
end: 100, // End number [uint]
duration: 2000, // Count duration [milisecond]
delay: 10, // Count delay [milisecond]
once: true, // Counting at once or recount when scroll [boolean]
pulse: false, // Pulse count for certain time [boolean|milisecond]
decimals: 0, // Decimal places [uint]
legacy: true, // If this is true it will use the scroll event listener on browsers
filesizing: false, // Is it for filesize?
currency: false, // Is it for currency? Use it for set the symbol too [boolean|char|string]
separator: false, // Do you want to use thausands separator? use it for set the symbol too [boolean|char|string]
formater: "us-US", // Number toLocaleString locale/formater, by default is "en-US" [string|boolean:false]
selector: ".purecounter", // HTML query selector for spesific element
};
/** Set default configuration based on user input */
this.configOptions = this.setOptions(options, this.defaults);
/** Get all elemenets based on default selector */
this.elements = document.querySelectorAll(this.configOptions.selector);
/** Get browser Intersection Listener Support */
this.intersectionSupport = this.intersectionListenerSupported();
/** Initiate event listened */
this.registerEventListeners();
}
/** This method is for create and merge configuration */
setOptions(config, baseConfig = {}) {
// Create new Config object;
var newConfig = {};
// Loop config items to set it value into newConfig
for (var key in config) {
// if baseConfig is set, only accept the baseconfig property
if (Object.keys(baseConfig).length !== 0 && !baseConfig.hasOwnProperty(key))
continue;
// var parse the config value
var val = this.parseValue(config[key]);
// set the newConfig property value
newConfig[key] = val;
// Exclusive for 'duration' or 'pulse' property, recheck the value
// If it's not a boolean, just set it to milisecond uint
if (key.match(/duration|pulse/)) {
newConfig[key] = typeof val != "boolean" ? val * 1000 : val;
}
}
// Finally, we can just merge the baseConfig (if any), with newConfig.
return Object.assign({}, baseConfig, newConfig);
}
/** Initial setup method */
registerEventListeners() {
/** Get all elements with class 'purecounter' */
var elements = this.elements;
/** Return if no elements */
if (elements.length === 0) return;
/** Run animateElements base on Intersection Support */
if (this.intersectionSupport) {
var intersectObserver = new IntersectionObserver(
this.animateElements.bind(this),
{
root: null,
rootMargin: "20px",
threshold: 0.5,
}
);
elements.forEach((element) => {
intersectObserver.observe(element);
});
} else {
if (window.addEventListener) {
this.animateLegacy(elements);
window.addEventListener(
"scroll",
function (e) {
this.animateLegacy(elements);
},
{ passive: true }
);
}
}
}
/** This legacy to make Purecounter use very lightweight & fast */
animateLegacy(elements) {
elements.forEach((element) => {
var config = this.parseConfig(element);
if (config.legacy === true && this.elementIsInView(element)) {
this.animateElements([element]);
}
});
}
/** Main Element Count Animation */
animateElements(elements, observer) {
elements.forEach((element) => {
var elm = element.target || element; // Just make sure which element will be used
var elementConfig = this.parseConfig(elm); // Get config value on that element
// console.log(elementConfig);
// If duration is less than or equal zero, just format the 'end' value
if (elementConfig.duration <= 0) {
return (elm.innerHTML = this.formatNumber(
elementConfig.end,
elementConfig
));
}
if (
(!observer && !this.elementIsInView(element)) ||
(observer && element.intersectionRatio < 0.5)
) {
var value =
elementConfig.start > elementConfig.end
? elementConfig.end
: elementConfig.start;
return (elm.innerHTML = this.formatNumber(value, elementConfig));
}
// If duration is more than 0, then start the counter
setTimeout(() => {
return this.startCounter(elm, elementConfig);
}, elementConfig.delay);
});
}
/** This is the the counter method */
startCounter(element, config) {
// First, get the increments step
var incrementsPerStep =
(config.end - config.start) / (config.duration / config.delay);
// Next, set the counter mode (Increment or Decrement)
var countMode = "inc";
// Set mode to 'decrement' and 'increment step' to minus if start is larger than end
if (config.start > config.end) {
countMode = "dec";
incrementsPerStep *= -1;
}
// Next, determine the starting value
var currentCount = this.parseValue(config.start);
// And then print it's value to the page
element.innerHTML = this.formatNumber(currentCount, config);
// If the config 'once' is true, then set the 'duration' to 0
if (config.once === true) {
element.setAttribute("data-purecounter-duration", 0);
}
// Now, start counting with counterWorker using Interval method based on delay
var counterWorker = setInterval(() => {
// First, determine the next value base on current value, increment value, and count mode
var nextNum = this.nextNumber(currentCount, incrementsPerStep, countMode);
// Next, print that value to the page
element.innerHTML = this.formatNumber(nextNum, config);
// Now set that value to the current value, because it's already printed
currentCount = nextNum;
// If the value is larger or less than the 'end' (base on mode), then print the end value and stop the Interval
if (
(currentCount >= config.end && countMode === "inc") ||
(currentCount <= config.end && countMode === "dec")
) {
element.innerHTML = this.formatNumber(config.end, config);
// If 'pulse' is set ignore the 'once' config
if (config.pulse) {
// First set the 'duration' to zero
element.setAttribute("data-purecounter-duration", 0);
// Next, use timeout to reset it duration back based on 'pulse' config
setTimeout(() => {
element.setAttribute(
"data-purecounter-duration",
config.duration / 1000
);
}, config.pulse);
}
// Now, we can close the conterWorker peacefully
clearInterval(counterWorker);
}
}, config.delay);
}
/** This method is to generate the element Config */
parseConfig(element) {
// Next, get all 'data-precounter-*' attributes value. Store to array
var configValues = [].filter.call(element.attributes, function (attr) {
return /^data-purecounter-/.test(attr.name);
});
// Now, we create element config as an object
var elementConfig =
configValues.length != 0
? Object.assign(
{},
...configValues.map(({ name, value }) => {
var key = name.replace("data-purecounter-", "").toLowerCase(),
val = this.parseValue(value);
return { [key]: val };
})
)
: {};
// Last setOptions and return
return this.setOptions(elementConfig, this.configOptions);
}
/** This method is to get the next number */
nextNumber(number, steps, mode = "inc") {
// First, get the exact value from the number and step (int or float)
number = this.parseValue(number);
steps = this.parseValue(steps);
// Last, get the next number based on current number, increment step, and count mode
// Always return it as float
return parseFloat(mode === "inc" ? number + steps : number - steps);
}
/** This method is to get the converted number */
convertNumber(number, config) {
/** Use converter if filesizing or currency is on */
if (config.filesizing || config.currency) {
number = Math.abs(Number(number)); // Get the absolute value of number
var baseNumber = 1000, // Base multiplying treshold
symbol =
config.currency && typeof config.currency === "string"
? config.currency
: "", // Set the Currency Symbol (if any)
limit = config.decimals || 1, // Set the decimal limit (default is 1)
uint = ["", "K", "M", "B", "T"], // Number uint based exponent threshold
value = ""; // Define value variable
/** Changes base number and its uint for filesizing */
if (config.filesizing) {
baseNumber = 1024; // Use 1024 instead of 1000
uint = ["bytes", "KB", "MB", "GB", "TB"]; // Change to 'bytes' uint
}
/** Set value based on the threshold */
for (var i = 4; i >= 0; i--) {
// If the exponent is 0
if (i === 0) value = `${number.toFixed(limit)} ${uint[i]}`;
// If the exponent is above zero
if (number >= this.getFilesizeThreshold(baseNumber, i)) {
value = `${(
number / this.getFilesizeThreshold(baseNumber, i)
).toFixed(limit)} ${uint[i]}`;
break;
}
}
// Apply symbol before the value and return it as string
return symbol + value;
} else {
/** Return its value as float if not using filesizing or currency*/
return parseFloat(number);
}
}
/** This method will get the given base. */
getFilesizeThreshold(baseNumber, index) {
return Math.pow(baseNumber, index);
}
/** This method is to get the last formated number */
applySeparator(value, config) {
// Get replaced value based on it's separator/symbol.
function replacedValue(val, separator) {
// Well this is my regExp for detecting the Thausands Separator
// I use 3 groups to determine it's separator
// THen the group 4 is to get the decimals value
var separatorRegExp =
/^(?:(\d{1,3},(?:\d{1,3},?)*)|(\d{1,3}\.(?:\d{1,3}\.?)*)|(\d{1,3}(?:\s\d{1,3})*))([\.,]?\d{0,2}?)$/gi;
return val.replace(separatorRegExp, function (match, g1, g2, g3, g4) {
// set initial result value
var result = "",
sep = "";
if (g1 !== undefined) {
// Group 1 is using comma as thausands separator, and period as decimal separator
result = g1.replace(new RegExp(/,/gi, "gi"), separator);
sep = ",";
} else if (g2 !== undefined) {
// Group 2 is using period as thausands separator, and comma as decimal separator
result = g2.replace(new RegExp(/\./gi, "gi"), separator);
} else if (g3 !== undefined) {
// Group 3 is using space as thausands separator, and comma as decimal separator
result = g3.replace(new RegExp(/ /gi, "gi"), separator);
}
if (g4 !== undefined) {
var decimal = sep !== "," ? (separator !== "," ? "," : ".") : ".";
result += g4.replace(new RegExp(/\.|,/gi, "gi"), decimal);
}
// Returning result value;
return result;
});
}
// If config formater is not false, then apply separator
if (config.formater) {
// Now get the separator symbol
var symbol = config.separator // if config separator is setted
? typeof config.separator === "string" // Check the type of value
? config.separator // If it's type is string, then apply it's value
: "," // If it's not string (boolean), then apply comma as default separator
: "";
// Special exception when locale is not 'en-US' but separator value is 'true'
// Use it's default locale thausands separator.
if (config.formater !== "en-US" && config.separator === true) {
return value;
}
// Return the replaced Value based on it's symbol
return replacedValue(value, symbol);
}
// If config formater is false, then return it's default value
return value;
}
/** This method is to get formated number to be printed in the page */
formatNumber(number, config) {
// This is the configuration for 'toLocaleString' method
var strConfig = {
minimumFractionDigits: config.decimals,
maximumFractionDigits: config.decimals,
};
// Get locale from config formater
var locale = typeof config.formater === "string" ? config.formater : undefined;
// Set and convert the number base on its config.
number = this.convertNumber(number, config);
// Now format the number to string base on it's locale
number = config.formater
? number.toLocaleString(locale, strConfig)
: parseInt(number).toString();
// Last, apply the number separator using number as string
return this.applySeparator(number, config);
}
getLocaleSeparator() {
var regExp =
/^(?:(\d{1,3}(?:,\d{1,3})*(?:\.\d{0,3})?)|(\d{1,3}(?:\.\d{1,3})*(?:,\d{0,3})?)|(\d{1,3}(?:\s\d{1,3})*(?:,\d{0,3})?))$/i;
return;
}
/** This method is to get the parsed value */
parseValue(data) {
// If number with dot (.), will be parsed as float
if (/^[0-9]+\.[0-9]+$/.test(data)) {
return parseFloat(data);
}
// If just number, will be parsed as integer
if (/^[0-9]+$/.test(data)) {
return parseInt(data);
}
// If it's boolean string, will be parsed as boolean
if (/^true|false/i.test(data)) {
return /^true/i.test(data);
}
// Return it's value as default
return data;
}
/** This method is to detect the element is in view or not. */
elementIsInView(element) {
var top = element.offsetTop;
var left = element.offsetLeft;
var width = element.offsetWidth;
var height = element.offsetHeight;
while (element.offsetParent) {
element = element.offsetParent;
top += element.offsetTop;
left += element.offsetLeft;
}
return (
top >= window.pageYOffset &&
left >= window.pageXOffset &&
top + height <= window.pageYOffset + window.innerHeight &&
left + width <= window.pageXOffset + window.innerWidth
);
}
/** Just some condition to check browser Intersection Support */
intersectionListenerSupported() {
return (
"IntersectionObserver" in window &&
"IntersectionObserverEntry" in window &&
"intersectionRatio" in window.IntersectionObserverEntry.prototype
);
}
}