Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
We have a website, on the front page we show "Parcels Shipped", we'd love the numbers to updated via a formula - i.e. we shipped 34,502,233 parcels in 2014... We show a static stat.... But we'd love to have the numbers increased via a formula that increases the number by the second/minute
Thanks for all the replies guys - So we current have this: gyazo.com/d421a3675884e2610d368c9e60e8acca
we want it to increase around 76 times per minute.... so a rotating number basically - i've no idea how to achieve this. (left number) & We want it to increase around 43 times per minute for middle number
Does anyone know where I can find this sort of trick?
This achieves your desired functionality using setInterval() to fire a function that checks to see how long it's been since today. Then, multiplying by the increase you mentioned in the comments and adding it to the numbers in your screenshot.
JS:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function timeSince() {
var prevTime = new Date(2015,8,8,0,0);
var thisTime = new Date();
return (thisTime.getTime() - prevTime.getTime()) / 1000;
}
function parcelCount() {
var secDiff = timeSince();
var leftNum = document.getElementById("left");
var midNum = document.getElementById("mid");
var leftNumCount = Math.round(((76/60) * secDiff) + 40093794);
var midNumCount = Math.round(((43/60) * secDiff) + 22874098);
leftNum.innerHTML = numberWithCommas(leftNumCount);
midNum.innerHTML = numberWithCommas(midNumCount);
}
parcelCount();
setInterval(parcelCount, 1000);
HTML:
<h3>Left</h3>
<span id="left"></span>
<h3>Mid</h3>
<span id="mid"></span>
Demo: http://jsfiddle.net/hopkins_matt/513ng07d/
Used info from these answers to build this:
https://stackoverflow.com/a/2901298/4556503
https://stackoverflow.com/a/6636639/4556503
Use setInterval with the increasing function as 1st argument and ms as the 2nd one.
var el = document.getElementById('counter')
var x = 0
window.setInterval(function(){
el.value = formula(++x)
}, 1000)
If the increase is completly random, just a "front-end design stuff" (sorry, guys), you can use setInverval() from Javascript.
It works this way:
every _s ms, the function will be called. If you have an increase factor, like a global constant you could do something like:
var myDiv = document.getElementById("myId");
var _mseconds = 1500; // mileseconds
var incFactor = 150;
var handlerInt = setInverval(function() {
myDiv.innerHTML = incFactor+incFactor; // you can use Math.Random() or something, instead
}, _mseconds);
Hope it helps!
Related
This question already has answers here:
Run JavaScript function at regular time interval
(4 answers)
Closed 2 years ago.
I am trying to make a script where while var < 1, it pastes letters, but it makes my screen crash. I tried seeing some questions here on StackOverflow, but the code doesn't line up with mine. I want the interval to be every 2 milliseconds
My code:
<template>
a
</template>
<html>
<head>a</head>
<body onLoad="pasteContent()">
</body>
<script>
while (true) {
function pasteContent() {
var i = 0;
var temp = document.getElementsByTagName("template")[0];
var clon = temp.content.cloneNode(true);
document.body.appendChild(clon);
}
}
</script>
</html>
Use setTimeout? Just set the timeout to 2 since it uses milliseconds.
Here's an article on it: https://www.w3schools.com/jsref/met_win_settimeout.asp
Use setInterval():
let div = document.querySelector('.div')
let intervalId = setInterval(writeLetter, 1000)
function writeLetter(){
if(div.innerHTML === 'aaaa'){
clearInterval(intervalId)
}else{
div.innerHTML += 'a'
}
}
<div class='div'></div>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I work with JavaScript on my bachelor thesis.
I would like to read a string and mark the elements that are the same and follow each other in the same color.
I have not found a good approach yet.
I would be grateful for a good proposal.
This is what i have right now.
function colorsetting(input){
var collength = input.length;
var now = '', last2 = '', colored = '';
now = last2 = input[0];
for(var i = 1; i <= collength, i++){
if(now !== last2){
colored = last2.fontcolor("green");
last2 = now;
}
now = input[i];
}
colored = last2.fontcolor("red");
return colored;
}
You can split up your input string using a regex:
/(.)\1*/g
(.) grabs any character, and stores that in capture group 1.
\1* then tells the regex to match as many of those as it can.
Then, iterate over that array, wrap the strings in a span, each with their own colour.
const str = "aaaabbbb123aaaaccccz";
const result = str.match(/(.)\1*/g);
console.log(result);
result.forEach(t => {
// Create a span element
const span = document.createElement("span");
// Set the text in that span to be the current match
span.innerText = t;
// Set the span's color to something random.
span.style.color = "#"+((1<<24)*Math.random()|0).toString(16);
document.body.append(span);
})
(random color code from here)
I have four '.dist' elements. They have a different preloaded data (exactly: 57 , 27 , 17 , 244). I want to animate incrementing, and I wrote this code:
$('.dist').each(function() {
var count = parseInt($(this).text())
var incr = 0
var that = $(this)
var animation_time = 500
var interv = animation_time / count
$(this).text('0')
var fd = setInterval(function() {
if (incr < count){
incr++
that.text(parseInt(incr))
}
} , interv)
console.log(interv)
})
The problem: The biggest value finishes 100 light years after the rest.
Console.log (directly from this code) returns:
8.928571428571429
18.51851851851852
29.41176470588235
2.0491803278688523
Thats the values which I/We expected, but I think every interval has a specific delay, but I dont't know how to detect and correct that delay.
I want to finish all of incrementations from 0 to 'var count' in time ~= 500ms. I want to start all of incrementations in the same time, and finish every one in the same time.
Sorry for my primitive querstion but I started my adventure with js/jq only 6 months ago, and I can't find the answer by google. Maybe I'm retarted or something. Thanks for help.
edit: html
<div class="info back2 border corners1">
<span class="dist">56</span> seriali<br>
<span class="dist">27</span> obejrzanych<br>
<span class="dist">17</span> oczekuje<br>
<span class="dist">244</span> sezonów<br>
</div>
You have two problems: One is that you end up with a very small interval, and second that the calculated interval becomes a float. SetInterval can only handle whole milliseconds, not fractions, so your calculation will always be off. Better to set a start and end time and calculate the difference.
This is the most accurate way to do time calculations in Javascript anyways.
$('.dist').each(function() {
var count = parseInt($(this).text());
var incr = 0;
var that = $(this);
var animation_time = 500;
$(this).text('0');
var time_start = new Date();
var fd = setInterval(function() {
var time_passed = new Date() - time_start;
if (time_passed >= animation_time) {
clearInterval(fd);
time_passed = animation_time;
}
that.text(Math.round(count*time_passed/animation_time));
} , 10);
})
http://jsfiddle.net/xau91msr/
Or if you don't care about the actual time for the animation and want browser stutters etc to not count as passed time you can increment time_passed yourself:
http://jsfiddle.net/jevjyf3m/
If you have a fixed number of steps and increment proportionally, then your counts will reach their ends together, also don't forget to clear the interval once the animation is complete.
http://jsfiddle.net/rtvtdasz/10
clearInterval(fd);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm trying to modify an element in jQuery programmatically, i.e. a number in docID increments up to a maximum number. I'm replacing text on a series of images on a page from Download to View. If I use #ctl00_cphMainContent_dlProductList_ct100_ctl00_lnkProofDownload instead of docID in the $(docID).text(...) part of the code, the text gets replaced correctly. When I use the docID variable in its place, it doesn't work.
What am I doing wrong here?
Thanks.
var max = 10;
var count = 100;
var s1 = "#ctl00_cphMainContent_dlProductList_ct";
var s2 = "_ctl00_lnkProofDownload";
var docID = "";
for (i = 1; i <= max; i++)
{
docID = s1.concat (count++, s2);
$(document).ready(function() {
$(docID).text(function(i, oldText) {
return oldText === 'Download' ? 'View' : oldText;
});
});
}
This is the HTML code that is being modified. The word Download is replaced by View.
<a id="ctl00_cphMainContent_dlProductList_ctl00_ctl00_lnkProofDownload"
href="../../../Controls/StaticDocProof.ashx?qs=op/5WlcUxeg849UT973Mwf0ZnNcMLfe3JYAe7EnJORsdyETYV1vcKaj0ROc2VrN5fXfYjO2MM6BUYXzX2UKmog=="
>Download</a>
It looks like you have done a couple things incorrectly in your code, including using a 1 instead of an l. If it was supposed to be a 100 instead of a l00, something more like this would work:
jQuery(function () {
var max = 10,
count = 100,
s1 = 'ctl00_cphMainContent_dlProductList_ct',
s2 = '_ctl00_lnkProofDownload',
docID;
for (var i = count; i <= count + max; i++) {
docID = s1 + i + s2;
jQuery('#' + docID).text(function (idx, oldText) {
return oldText === 'Download' ? 'View' : oldText;
});
}
});
Fiddle here: http://jsfiddle.net/ochguL2d/
Otherwise, let us know if it is supposed to be l00 for a different answer.
Your a element has this in the middle (note two "els"):
ctl00_ctl00
… but your docID has this in the middle (note a "one and an el"):
ct100_ctl00
Fix your HTML, and your code works as-is: http://jsfiddle.net/5c7hwyts/
However, that's an odd way to write jQuery.
Here's a different approach:
$('a').text(function(i, oldText) {
var num= parseInt(this.id.split('ctl00_cphMainContent_dlProductList_ct')[1]);
if(num>=100 && num<110) {
return oldText === 'Download' ? 'View' : oldText;
}
});
Fiddle
The element IDs your are trying to match in your code are not the ones in the DOM.
// This is what you want to match
var domID = "#ctl00_cphMainContent_dlProductList_ct100_ctl00_lnkProofDownload"
^ that is an L
// this what your code is trying to match in its first iteration
var docID = "#ctl00_cphMainContent_dlProductList_ct10_ctl00_lnkProofDownload";"
^ that is a 1 (one)
Also, your code's max variable needs to be a two char numeric string with leading zeros starting at zero, not an integer starting at 10.
Personally, I would just:
// On DomReady...
$(document).ready(function() {
// loop through all anchors that have "lnkProofDownload" in their ID attribute
$('a[id*="lnkProofDownload"]').each(function() {
// and if the text is set to "Download", change it to "View"
if ($(this).text() == "Download") {
$(this).text("View");
}
});
});
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm new to query/javascript and having a problem with the following code to calculate a gross value and tax amount based
on the net amount the user enters. The user will enter a double amount and the gross and vat amounts are also defined as doubles.
Can anyone help? I get an error: "Uncaught SyntaxError: Unexpected number" when i try running the following code.
$('#netPayment').change(calcLowerVatRateAndGrossAmount);
/* $('#netPayment').change(function(){
calcLowerVatRateAndGrossAmount();
}); */
});
function calcVatRateAndGrossAmount(){
var netPayment = parseFloat($('#netPayment').val());
var vatAmount = 00.0;
var VatRate = 20.0;
var grossPayment = 0.00;
var totalPaymentAmount = 0.00;
if (netPayment !== '') {
vatAmount = (netPayment * VatRate) / 100;
grossPayment = (netPayment - vatAmount);
$('#vatAmount').val(parseFloat(vatAmount.data).toFixed(2));
$('#grossPayment').val(parseFloat(grossPayment.data).toFixed(2));
} else {
$('#vatAmount').val(vatAmount.amountNull);
$('#grossPayment').val(grossPayment.amountNull);
}
};
So you calculate a number here
vatAmount = (netPayment * VatRate) / 100;
And in here, you treat vatAmount as an object that has a key data
$('#vatAmount').val(parseFloat(vatAmount.data).toFixed(2));
You should just be using the variable. A simple test
console.log("variable itself: ", vatAmount);
console.log("key data: ", vatAmount.data);
So you would need to just do
$('#vatAmount').val(vatAmount.toFixed(2));
$('#grossPayment').val(grossPayment.toFixed(2));
You do the same thing with grossPayment and you reference some other property vatAmount.amountNull
$('#vatAmount').val(vatAmount.amountNull);
$('#grossPayment').val(grossPayment.amountNull);
should be
$('#vatAmount').val(""); //or any error message
$('#grossPayment').val("");