I have this following code that automatically increments a number. I want to increment the number based on the expected value. then stop the increment. Please see below the code
var expected_value = 1000;
var val = expected_value - 60;
$("#counter").val(val);
function numberFormat(n) {
n += '';
x = n.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
(function loop() {
setTimeout(function() {
var counter = document.getElementById('counter');
var current = parseInt(counter.value.replace(',', ''));
var max_add = 1;
var min_add = 1;
if (counter.value == expected_value) {
counter.value = true_value;
} else {
counter.value = numberFormat(current + Math.floor(Math.random() * max_add + min_add));
}
loop();
}, 100);
}());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="counter" type="text" readonly="true">
You could validate the looped value and expected value before recursive loop call
Updated
its stop if max_add change or else loop value hit above expected_value
var expected_value = 1000;
var val = expected_value - 60;
$("#counter").val(val);
function numberFormat(n) {
n += '';
x = n.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
setTimeout(function(){
max_add = Math.random()
},3000)
var max_add = 1,new_add = 1;
var val = 0;
(function loop() {
setTimeout(function() {
var counter = document.getElementById('counter');
var current = parseInt(counter.value.replace(',', ''));
var min_add = 1;
if (counter.value == expected_value) {
counter.value = true_value;
} else {
val = current+Math.floor(Math.random()*10)+ Math.floor(Math.random() * max_add + min_add);
counter.value = numberFormat(val);
}
if (val <= expected_value && max_add == new_add) { //matching the loop value and expected value
loop();
}
new_add = max_add
}, 100);
}());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="counter" type="text" readonly="true">
Related
I have 2 option in radio input
Tab screen to stop in 0.5 sec -> So I complete this solution.
Tab screen to stop immediately. I want it spin after I press the submit button and it stops after I tab the screen.
Here is my fiddle here: https://jsfiddle.net/7det89o6/3/
$("#submit-btn").click(function() {
var cond = valRadioFunc();
if (cond == 1) {
$('.reel-container:first').slotMachine('00' + 1).toString();
// one click
$(".bg-img").one("click", function() {
$('.reel-container:first').slotMachine(randGen());
});
} else if (cond == 2) {
$('.reel-container:first').slotMachine('00' + 1).toString();
}
});
}
<script type="text/javascript">
var reeling_time = 500;
var stop_spinning_time_difference = 350;
var start_spinning_time = 0;
var currency_symbol = "$";
var isInfinity = false;
$(document).ready(function() {
$(document).on('show.bs.modal', '.modal', function() {
function valRadioFunc() {
var valRadio = $('input[name=radio]:checked', '#form-select').val();
return valRadio;
}
$("#submit-btn").click(function() {
var cond = valRadioFunc();
if (cond == 1) {
$('.reel-container:first').slotMachine('00' + 1).toString();
// one click
$(".bg-img").one("click", function() {
isInfinity = false;
$('.reel-container:first').slotMachine(randGen());
});
} else if (cond == 2) {
$('.reel-container:first').slotMachine('00' + 1).toString();
isInfinity = true;
// one click
$(".bg-img").one("click", function() {
reeling_time = 0;
isInfinity = false;
$('.reel-container:first').slotMachine(randGen());
});
}
});
});
});
function randGen() {
var minRange = 1;
var maxRange = 999;
var randNum = (Math.floor(Math.random() * maxRange) + minRange).toString();
if (randNum.toString().length == 3) {
return randNum;
} else if (randNum.toString().length == 2) {
return "0" + randNum;
} else if (randNum.toString().length == 1) {
reeling_time = 0;
return "00" + randNum;
}
}
function collision($div1, $div2) {
var x1 = $div1.offset().left;
var w1 = 40;
var r1 = x1 + w1;
var x2 = $div2.offset().left;
var w2 = 40;
var r2 = x2 + w2;
if (r1 < x2 || x1 > r2) return false;
return true;
}
$.fn.slotMachine = function(my_number) {
var $parentSlot = this;
var hidden_reels_html = '';
var hidden_reels_array = [];
var numberFormat = function number_format(number) {
number = (number + '');
return number;
}
for (var $j = 0; $j <= 9; $j++) {
hidden_reels_array[$j] = "";
for (var $i = 0; $i <= 9; $i++) {
hidden_reels_array[$j] += '<div class="reel-symbol' + ($i == 0 ? ' reel-loop' : '') + '">' + (($j + $i) % 10) + '</div>';
}
}
var transformNumberToArrayPlusDollar = function(my_number) {
var my_scale = parseInt(my_number, 10) > 999 ? 0 : 2;
my_number = numberFormat(my_number, my_scale, ".", ",");
var my_number_array = my_number.split('');
// my_number_array.unshift(currency_symbol);
return my_number_array;
};
//Effect for the reel to go up and then down like it is pushed to spin
var effectBeforeSpin = function() {
$parentSlot.find('.main-reel-symbol').removeClass('reel-stop').addClass('reel-begin');
};
var slotMachine = function(my_number) {
var my_number_array = transformNumberToArrayPlusDollar(my_number);
var reels_html = '';
for (var $i = 0; $i < my_number_array.length; $i++) {
reels_html += '<div class="reel">' + hidden_reels_array[($i % 10)] + '</div>';
}
effectBeforeSpin();
var startSpinning = function() {
$parentSlot.html(reels_html);
var my_timer = reeling_time;
$.each(my_number_array, function(my_index, my_value) {
var next_value = /^[0-9]$/.test(my_value) ? (parseInt(my_value, 10) + 1) % 10 : "0";
var stopSpinning = function() {
$parentSlot.find('.reel:eq(' + my_index + ')')
.html("<div class='reel-symbol main-reel-symbol reel-stop'>" + my_value + "</div>")
.append("<div class='reel-symbol'>" + next_value + "</div>");
};
if(!isInfinity){
setTimeout(stopSpinning, my_timer);
}
my_timer += stop_spinning_time_difference;
});
};
setTimeout(startSpinning, start_spinning_time);
};
slotMachine(my_number);
return this;
};
$('.reel-container:first').slotMachine('00' + 1).toString();
</script>
I add one variable at top of JavaScript code.
i have this javascript that displays a clock. Is it also possible that it display realtime an div on special time?
if (today >= 12 && today <= 13.30) {
document.body.className += 'lunchbreak';
} else {
document.body.className += 'nolunchbreak';
}
Used clock javascript:
function timepadding(x5) {
if (typeof x5 !== "string") {
x5 = x5.toString()
}
var x6 = 0;
var x7 = 0;
if (x5 % 60 === 0) {
return x5 + ":00"
}
else {
x6 = x5 % 60;
return x6.toString()
}
}
function gettimezone() {
var d = new Date();
var z = document.getElementById("result");
var utcsinceepoch = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
var y1 = d.getTime()
z.innerHTML= (utcsinceepoch - d.getTime())/3600000;
}
gettimezone();
function utcoffset(time, offset) {
return time + offset;
}
function displayTime() {
var d = new Date();
var y = document.getElementById("a");
var h = (d.getHours()).toString();
var m = (d.getMinutes()).toString();
var s = (d.getSeconds()).toString();
var h2 = ("0" + h).slice(-2);
var m2 = ("0" + m).slice(-2);
var s2 = ("0" + s).slice(-2);
y.style.fontSize = "100px";
y.innerHTML= h2 + ":" + m2 + ":" + s2;
}
setInterval(displayTime, 1000);
I hope you have ideas :)
https://jsbin.com/xubimewoke/edit?html,js,output
I'm using Raphael.js to help in creating a Stripchart, but unfortunately it's not displaying the actual data in IE8. The grid for the chart is displaying but that's about it. Does anything in the code jump out at you as to why this may be an issue? Just looking for a second set of eyes, thanks!
/*
* accelerometer charts, needs raphael-min.js
*/
function Stripchart(element) {
var ret = new SChart(element);
return ret;
}
function SChart(element) {
vpwidth = element.offsetWidth;
vpheight = element.offsetHeight;
tzero = 0;
mspertick = 100.0;
bwidth = 0;
bheight = 0;
mgperpx = 1000.0 / 30.0;
chanwidth = 2;
labelheight = 8;
labelevery = 30000;
arraymax = vpwidth * (mspertick/5) * 2;
xchan = new Array(arraymax);
ychan = new Array(arraymax);
zchan = new Array(arraymax);
clock = new Array(arraymax);
head = 0;
tail = 0;
Paper = Raphael(element, vpwidth, vpheight);
this.svg_line = function(x1, y1, x2, y2) {
var ret = "M" + parseInt(x1) + " " + parseInt(y1) + " L" + parseInt(x2) + " " + parseInt(y2);
return ret;
}
this.clear = function() {
Paper.clear();
}
this.draw_grid = function(torigin) {
epsilon = this.clockToTick(torigin-tzero) % 10;
yzero = vpheight / 2;
tline = 0;
tlast = (parseInt(torigin/labelevery) + 1) * labelevery;
for (i = vpwidth-bwidth - epsilon ; i > bwidth; i-= 10) {
svg = this.svg_line(i, bheight, i, vpheight-bheight);
l = Paper.path(svg);
l.attr("stroke", "#eee");
l.attr("stroke-width", "1");
l.attr("opacity", 0.75);
}
for (i = 0; i < torigin-tzero; i += labelevery) {
if(i > torigin - this.tickToClock(vpwidth-bwidth*2) - tzero) {
xpos = vpwidth - bwidth - this.clockToTick(torigin - tzero - i);
minutes = parseInt(i/60000);
seconds = parseInt((i%60000)/1000);
if(seconds < 10) {
seconds = "0" + seconds;
}
timestring = "" + minutes + ":" + seconds;
Paper.text(xpos, vpheight-bheight-(labelheight/2)-1, timestring);
}
}
for (i = yzero; i > bheight; i -= 15) {
svg = this.svg_line(bwidth, i, vpwidth-bwidth, i);
l = Paper.path(svg);
l.attr("stroke", "#eee");
l.attr("stroke-width", "1");
l.attr("opacity", 0.75);
}
for (i = yzero; i < vpheight-bheight; i += 15) {
svg = this.svg_line(bwidth, i, vpwidth-bwidth, i);
l = Paper.path(svg);
l.attr("stroke", "#eee");
l.attr("stroke-width", "1");
l.attr("opacity", 0.75);
}
var svg = this.svg_line(bwidth, yzero, vpwidth-bwidth, yzero);
var l = Paper.path(svg);
l.attr("stroke-width", "1");
l.attr("stroke", "#ddd");
l.attr("opacity", 0.75);
var r = Paper.rect(bwidth, bheight, vpwidth-bwidth*2, vpheight-bheight*2);
r.attr("stroke-width", "2");
r.attr("stroke", "#ccc");
r.attr("opacity", 0.75);
}
this.draw_channel = function(data, color) {
var now;
var svg_path = ""
var mean_datum = 0;
var this_tick;
var prev_tick;
var count;
var xorig = vpwidth-bwidth;
var yorig = vpheight / 2;
// this.text(150, 40, "head = " + head + " tail = " + tail);
if (head == tail) {
return;
}
i = this.prev(head);
now = this.clockToTick(clock[i]);
prev_tick = now;
count = 0;
mean_datum = 0;
// this.text(150, 30, now + " " + i);
// console.log("Start " + this.prev(head) + " end " + this.prev(tail) + " max " + arraymax);
for(i = this.prev(head); i != this.prev(tail); i = this.prev(i)) {
this_tick = this.clockToTick(clock[i]);
if(this_tick == prev_tick) {
mean_datum += data[i];
++count;
} else {
mean_datum = parseInt(mean_datum / count);
if(svg_path.length == 0) {
svg_path = "M";
} else {
svg_path += "L";
}
svg_path += parseInt(xorig - now + prev_tick) + " ";
yplot = yorig - this.chanToPx(mean_datum);
if(yplot < 1) {
yplot = 1;
} else if(yplot > vpheight - bheight) {
yplot = vpheight - bheight;
}
svg_path += parseInt(yplot);
mean_datum = data[i];
count = 1;
prev_tick = this_tick;
}
if(xorig - now + this_tick <= bwidth) {
break;
}
}
var chan_path = Paper.path(svg_path);
if(color == "#00f") {
// console.log(svg_path);
}
chan_path.attr("stroke", color);
chan_path.attr("stroke-path", 1);
chan_path.attr("stroke-width", chanwidth);
chan_path.attr("opacity", 0.9);
}
this.text = function(x, y, s) {
Paper.text(x, y, s);
}
this.prev = function(index) {
var ret;
ret = index - 1;
if(ret <= 0) {
ret += arraymax;
}
return ret;
}
this.next = function(index) {
var ret;
ret = index + 1;
if(ret >= arraymax) {
ret -= arraymax;
}
return ret;
}
this.dequeue = function() {
if(head != tail) {
tail = this.next(tail);
}
}
this.enqueue = function() {
var ret = head;
head = this.next(head);
// detect collision
if(this.next(head) == tail) {
this.dequeue();
}
return ret;
}
this.add_datum = function(time, x, y, z) {
// assume java applet has already handled clock rollover
var entry = this.enqueue();
if(tzero == 0) {
tzero = parseInt(time);
}
clock[entry] = parseInt(time);
xchan[entry] = parseInt(x);
ychan[entry] = parseInt(y);
zchan[entry] = parseInt(z);
// console.log("Adding datum " + entry + " head " + head + " tail " + tail);
// clock[head] = parseInt((parseInt(time) + (mspertick / 2)) / mspertick);
// xchan[head] = parseInt((parseInt(x) + (mgperpx / 2)) / mgperpx);
// ychan[head] = parseInt((parseInt(y) + (mgperpx / 2)) / mgperpx);
// zchan[head] = parseInt((parseInt(z) + (mgperpx / 2)) / mgperpx);
// this.text(150, 30, "(" + clock[head] + ", " + xchan[head] + ", " + ychan[head] + ", " + zchan[head] + ")");
// while(clock[head] - clock[tail] > vpwidth - (bwidth * 2)) {
// tail++;
// if (tail >= arraymax) {
// tail -= arraymax;
// }
// }
}
this.tickToClock = function(tick) {
ret = tick * mspertick;
return ret;
}
this.clockToTick = function(clock_ms) {
ret = parseInt(((mspertick / 2) + clock_ms) / mspertick);
return ret;
}
this.chanToPx = function(chan) {
ret = parseInt((chan + (mgperpx / 2)) / mgperpx);
return ret;
}
this.draw = function() {
var top = this.prev(head);
this.clear();
this.draw_grid(clock[top]);
this.draw_channel(xchan, "#00f");
this.draw_channel(ychan, "#0f0");
this.draw_channel(zchan, "#f00");
}
this.reset = function() {
tzero = 0;
head = 0;
tail = 0;
}
this.add_test_datum = function(tick) {
// add some jitter +/- 16ms
time = tick * mspertick + 16 - Math.floor(Math.random() * 32);
x = Math.floor(Math.random() * 1000) - Math.floor(Math.random() * 1000);
y = 1000 + Math.floor(Math.random() * 1000) - Math.floor(Math.random() * 1000);
z = -1000 + Math.floor(Math.random() * 1000) - Math.floor(Math.random() * 1000);
time = "" + time;
x = "" + x;
y = "" + y;
z = "" + z;
this.add_datum(time, x, y, z);
}
this.test_animate = function(self) {
var tid;
var tcount = 0;
var tmax = 500;
function interval_display() {
for (i=0 ; i<10; i++) {
tcount++;
self.add_test_datum(tcount);
}
self.draw(tcount);
if(tcount > tmax) {
clearInterval(tid);
}
}
tid = setInterval(interval_display, 2500);
}
}
I would like to add a $5.00 charge whenever the txtBwayEDUGift checkbox is selected. The javascript code I currently have is reducing the amount when checkbox is unchecked, but not applying the charge when selected. I can provide additonal code if needed.
Here is my input type from my aspx page:
<input type="checkbox" name="txtBwayEDUGift" id="txtBwayEDUGift" onchange="checkboxAdd(this);" checked="checked" />
Here is my javascript:
{
var divPrevAmt;
if (type == 0)
{
divPrevAmt = document.getElementById("divBwayGiftPrevAmt");
}
else if (type == 1)
{
divPrevAmt = document.getElementById("divBwayEDUGiftPrevPmt");
}
var txtAmt = document.getElementById(obj);
var amt = txtAmt.value;
amt = amt.toString().replace("$","");
amt = amt.replace(",","");
var prevAmt = divPrevAmt.innerHTML;
try
{
amt = amt * 1;
}
catch(err)
{
txtAmt.value = "";
return;
}
if (amt >= 0) //get the previous amount if any
{
if (type == 0)
{
if (prevAmt.toString().length > 0)
{
prevAmt = prevAmt * 1;
}
else
{
prevAmt = 0;
}
}
else if (type == 1)
{
if (prevAmt.toString().length > 0)
{
prevAmt = prevAmt * 1;
}
else
{
prevAmt = 0;
}
}
//now update the master total
var total = document.getElementById("txtTotal");
var dTotal = total.value.toString().replace("$","");
dTotal = dTotal.replace(",","");
dTotal = dTotal * 1;
var newTotal = dTotal - prevAmt;
newTotal = newTotal + amt;
divPrevAmt.innerHTML = amt.toString();
newTotal = addCommas(newTotal);
amt = addCommas(amt);
txtAmt.value = "$" + amt;
total.value = "$" + newTotal;
}
else
{
txtAmt.value = "";
return;
}
}
function disable()
{
var txtTotal = document.getElementById("txtTotal");
var txt = txtTotal.value;
txtTotal.value = txt;
var BwayGift = document.getElementById("txtBwayGift");
BwayGift.focus();
}
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
var newTotal = x1 + x2;
if (newTotal.toString().indexOf(".") != -1)
{
newTotal = newTotal.substring(0,newTotal.indexOf(".") + 3);
}
return newTotal;
}
function checkChanged()
{
var cb = document.getElementById("cbOperaGala");
if (cb.checked == true)
{
var tableRow = document.getElementById("trCheckbox");
tableRow.style.backgroundImage = "url('images/otTableRowSelect.jpg')";
}
else if (cb.checked == false)
{
var tableRow = document.getElementById("trCheckbox");
tableRow.style.backgroundImage = "";
}
}
function alertIf()
{
var i = 0;
for (i=5;i<=10;i++)
{
try{
var subtotal2 = document.getElementById("txtSubTotal" + i);
var dSubtotal2 = subtotal2.value;
dSubtotal2 = dSubtotal2.replace("$","");
dSubtotal2 = dSubtotal2 * 1;}
catch (Error){dSubtotal2 = 0}
if (dSubtotal2 > 0)
{
alert("You have selected the I want it all package, \n however you have also selected individual tickets to the same events. \n If you meant to do this, please disregard this message.");
break;
}
}
}
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
//Add $5.00 donation to cart
function checkboxAdd(ctl) {
if (ctl.checked == true) {
// alert("adding $5");
calculateTotal(5, "A");
} else {
// alert("deducting $5");
calculateTotal( 5, "S");
}
}
</script>
I do not understand the context of the scenario. When a user clicks the checkbox are you making an HTTP request to the server? Or is this a simple form POST page? What is calculateTotal() doing?
I figured it out. So the functionality I had in place was fine.
//Add $5.00 donation to cart
function checkboxAdd(txtBwayEDUGift) {
if (txtBwayEDUGift.checked == true) {
// alert("adding $5");
calculateTotal(5, "A");
} else {
// alert("deducting $5");
calculateTotal(5, "S");
}
}
But I needed to add a load function:
function load() {
calculateTotal(5, "A");
}
<body onload="load()">
Along with adding a reference to my c# page:
if (txtBwayEDUGift.Checked)
{
addDonations(5.00, 93);
}
You can use jQuery :)
$(txtBwayEDUGift).change(calculateTotal(5, "S"));
I was looking for a jquery countup timer that was based on the time of day, and I was struggling to find one so here I just wrote my own. Here it is for anyone who's looking for one.
The objective is to take the time of day, calculate a percentage through the day of that current time, multiply it by an objective sum and start adding to create a realistic timing scenario. My timers are firing to create the simulation of an unsteady data flow, but you can change it to a steady increase easily.
The element with the number is #counter, and the objective total is the 3.5mm.
var currentNumber;
$(document).ready(function (e) {
var currDate = new Date();
var mins = currDate.getMinutes();
var hours = currDate.getHours();
var seconds = currDate.getSeconds();
var combined = (hours * 60 * 60) + (mins * 60) + seconds;
var percentage = (combined / 90000);
var startingPoint = Math.round(3500000 * percentage);
currentNumber = startingPoint;
$('#counter').html(formatNumber(startingPoint));
setTimeout(function () {
updateNumber(currentNumber)
}, 100);
});
function updateNumber(startingPoint) {
if (startingPoint % 58 === 0) {
startingPoint += 5;
currentNumber = startingPoint;
$('#counter').html(formatNumber(currentNumber));
setTimeout(function () {
updateNumber(currentNumber)
}, 850);
} else if (startingPoint % 22 === 0) {
startingPoint += 4;
currentNumber = startingPoint;
$('#counter').html(formatNumber(currentNumber));
setTimeout(function () {
updateNumber(currentNumber)
}, 500);
} else if (startingPoint % 6 === 0) {
startingPoint += 1;
currentNumber = startingPoint;
$('#counter').html(formatNumber(currentNumber));
setTimeout(function () {
updateNumber(currentNumber)
}, 75);
} else {
startingPoint += 5;
currentNumber = startingPoint;
$('#counter').html(formatNumber(currentNumber));
setTimeout(function () {
updateNumber(currentNumber)
}, 250);
}
}
function formatNumber(number) {
return addCommas((number).toFixed(0));
}
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}