Changing the end of a number - javascript

I am having some serious trouble with my script... for some reason the console isn't talking to me and my output isn't showing up... What I'm trying to do here is get the output to be a thousand when the number reaches 1000 and million when the number reaches 1000000 and all the way to Quintilian. Please help!
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="output"></p>
<button onclick="collectWood()" id="woodButton">collect wood</button>
<script>
window.addEventListener("DOMcontentLoaded", function(){
var wood = +localStorage.getItem("woodSave");
var woodOut = document.getElementById("output");
var woodbtn = document.getElementById('woodButton');
woodThousand();
woodMillion();
woodBillion();
woodTrillion();
woodQuadrillion();
woodQuintillion();
woodbtn.addEventListener("click", collectWood);
function collectWood() {
wood +=1;
woodOut.innerHTML = wood;
localStorage.setItem("woodSave", wood);
woodThousand();
woodMillion();
woodBillion();
woodTrillion();
woodQuadrillion();
woodQuintillion();
}
function woodThousand() {
console.log(wood);
woodOut.textContent = (wood >= 1000) ? (wood / 1000).toFixed(2) + "Thousand":wood;
}
function woodMillion() {
woodOut.textContent = (wood >= 1000000) ? (wood / 1000000).toFixed(2) + "Million":wood;
}
function woodBillion() {
woodOut.textContent = (wood >= 1000000000) ? (wood / 1000000000).toFixed(2) + "Billion":wood;
}
function woodTrillion() {
woodOut.textContent = (wood >= 1000000000000) ? (wood / 1000000000000).toFixed(2) + "Trillion":wood;
}
function woodQuadrillion() {
woodOut.textContent = (wood >= 1000000000000000) ? (wood / 1000000000000000).toFixed(2) + "Quadrillion":wood;
}
function woodQuintillion() {
woodOut.textContent = (wood >= 1000000000000000000) ? (wood / 1000000000000000000).toFixed(2) + "Quintillion":wood;
}
setInterval(function() {
woodThousand();
woodMillion();
woodBillion();
woodTrillion();
woodQuadrillion();
woodQuintillion();
}, 1);
});
</script>
</body>
</html>

localStorage won't work on SO, so please see this Fiddle for a solution. Your code had some issues:
First it's DOMContentLoaded (with a capital "C"). That's why nothing happens when the page starts. Second, you don't need the onclick="collectWood() because that is being taken care of in the JavaScript.
Probably the biggest change is that you don't need a different function for each level that the wood count gets to. One function will do (see the if/then in the Fiddle).

Related

Format time to minutes and seconds in countdown/timer

I am building a pomodoro clock/countdown, but have an issue with formatting selected time to minutes/hours/seconds. I have tried to multiply the secs variable with 60 (secs*=60), but it makes a mess and I can't figure out how to fix it. So, I would like it to "know" that it needs to count down from 25 minutes - in 25:00 format, or more/less(hh:mm:ss) if the user chooses so with + and - buttons. All help very appreciated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1 id="num">25 min</h1>
<div id="status"></div>
<button onclick='countDown(secs, "status")'>Start countdown</button>
<button onclick='increaseNumber()'>+</button>
<button onclick='decreaseNumber()'>-</button>
<script src="script.js"></script>
</body>
</html>
and here is javascript:
var num = document.getElementById('num').innerHTML;
var secs = parseInt(num);
function countDown(secs, elem) {
var element = document.getElementById(elem);
secs--;
var timer = setTimeout(function() {
countDown(secs, elem);
}, 1000);
//secs *= 60;
if(secs%60 >= 10){ //10 - if it's not a single digit number
document.getElementById('num').innerHTML = (Math.floor(secs/60) + ":" + secs%60);
}
else{
document.getElementById('num').innerHTML = (Math.floor(secs/60) + ":" + "0" + secs%60);
}
element.innerHTML = "Please wait for "+secs+" minutes";
//if timer goes into negative numbers
if(secs < 1){
clearTimeout(timer);
element.innerHTML = '<h2>Countdown complete!</h2>';
element.innerHTML += 'Click here now';
}
}
function increaseNumber() {
secs += 5;
document.getElementById('num').innerHTML = secs + ' min';
}
function decreaseNumber() {
if(secs >= 10) {
secs -= 5;
document.getElementById('num').innerHTML = secs + ' min';
}
}
Is there a reason you're doing it by hand ?
If you don't mind using a library, moment.js does a very good job at time manipulations. It's lightweight and very easy to use.
If you have to do it by hand because of some limitations, what are they ?
For reference:
//Creates a moment. Its value is the time of creation
var timer = moment();
//add 60 seconds to the timer
timer.add(60, 's');
//Removes 1 minutes from the timer
timer.subtract(1, 'm');
Sources :
Add
Substract
Try this countDown function:
function countDown(secs, elem) {
var element = document.getElementById(elem);
element.innerHTML = "Please wait for "+secs+" minutes";
var second = 0;
var timer = setInterval(function(){
var extraZero = second < 10 ? '0' : '';
document.getElementById('num').innerHTML = secs + ":" + extraZero + second;
if (second-- === 0) {
second = 59;
if (secs-- === 0){
clearInterval(timer);
element.innerHTML = '<h2>Countdown complete!</h2>';
element.innerHTML += 'Click here now';
}
}
}, 1000);
}
Since you are counting down the seconds, it is making more sense to use setInterval instead of setTimeout.

Can't get form to hide in JS

Having this problem with trying to get a form to hide in Javascript.
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Timer</title>
<link rel="stylesheet" href="style.css">
<script src="javascript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="wrapper">
<div id="time">00:00:00</div>
<form id="myform">
<input type="text" autocomplete="off" id="box" placeholder="00:00:00" onkeypress="checkBox(event)">
</form>
</div>
</body>
</html>
And here is my JS:
function timer(time) {
document.getElementById("myform").style.display = "none";
document.getElementById("time").style.display = "inline";
var interval = setInterval(function () {
if (time == 0) {
time = 299;
} else {
var newTime = timeFormat(time);
document.getElementById("time").innerHTML = newTime;
document.title = newTime;
time--;
}
}, 1000);
}
function checkBox(event) {
if (event.keyCode == 13) {
var string = document.getElementById("box").value;
var numTest = string;
if (string.length != 0) {
var numOfColons = string.split(":").length - 1;
var hr = 0;
var min = 0;
var sec = 0;
if (numOfColons == 2) {
numTest = numTest.replace(":", "");
numTest = numTest.replace(":", "");
hr = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
min = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
sec = string.substring(0, string.length);
} else if (numOfColons == 1) {
numTest = numTest.replace(":", "");
min = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
sec = string.substring(0, string.length);
} else if (numOfColons == 0) {
sec = string;
}
hr = parseInt(hr);
min = parseInt(min);
sec = parseInt(sec);
if(/^\d+$/.test(numTest)) {
var totalSec = hr*3600 + min*60 + sec;
if (totalSec > 0) {
timer(totalSec);
}
}
}
}
}
function focus() {
document.getElementById("box").focus();
}
function timeFormat(time) {
var sec = time % 60;
var totalMin = time / 60;
var min = Math.floor(totalMin % 60);
var string = "";
if (min == 0 && sec < 10) {
string = "0:0" + sec;
} else if (min == 0) {
string = "0:" + sec;
} else if (sec < 10) {
string = min + ":0" + sec;
} else {
string = min + ":" + sec;
}
return string;
}
Note that I am not using a button to trigger the form submission, I am simply using a onkeypress event to detect if the user hit the enter button (I wanted a cleaner design). Whenever the timer function is called, the text box flickers like it turns off for a second, than it comes back on in an instant. I have no idea what the problem is. I also have gotten no errors in console.
Am not sure what you are trying to achieve but from looking at your code, Hitting enter results in the page being reloaded, so I can't get to see the result.
I would however suggest you use jQuery to hide show your results, since you are already calling the script
$('#myform').hide();
$('#time').show();
The problem is this line of code. It turns the form off for a split second, which causes the blinking effect to occur. Simply remove this or comment it out.
document.getElementById("myform").style.display = "none";
If you want to hide the form, use jQuery's $('#myForm').hide() function. It's similar to <form id="myform" style="display:none;">
You could also try this:
<input type="text" id="timeInputBox" autocomplete="off" id="box" placeholder="00:00:00" onkeypress="checkBox(event)">
With this:
document.getElementById('timeInputBox').style.display = "none"; // JS
Or use this:
$('#timeInputBox').hide(); // jQuery
You may also want to move the jQuery <script> tag up higher in your <head> block. It needs to go before your call to your external <script src="javascript.js"></script> tag. Then you can use the $ and all of these functions from api.jquery.com in your .js file.

JS function stopwatch application confuses the user

I wrote a javascript application but I end up with a total confusion. This js application needs to run in minutes, seconds, and hundredths of seconds. The part about this mess is when the stopwatch show, in this case 03:196:03. Here is my confusion. When the stopwatch shows 196, is it showing hundredth of seconds? Does anybody can check my function and tell me what part needs to be corrected in case that the function is wrong?
<html>
<head>
<title>my example</title>
<script type="text/javascript">
//Stopwatch
var time = 0;
var started;
var run = 0;
function startWatch() {
if (run == 0) {
run = 1;
timeIncrement();
document.getElementById("countDown").disabled = true;
document.getElementById("resetCountDown").disabled = true;
document.getElementById("start").innerHTML = "Stop";
} else {
run = 0;
document.getElementById("start").innerHTML = "Resume";
}
}//End function startWatch
function watchReset() {
run = 0;
time = 0;
document.getElementById("start").innerHTML = "Start";
document.getElementById("output").innerHTML = "00:00:00";
document.getElementById("countDown").disabled = false;
document.getElementById("resetCountDown").disabled = false;
}//End function watchReset
function timeIncrement() {
if (run == 1) {
setTimeout(function () {
time++;
var min = Math.floor(time/10/60);
var sec = Math.floor(time/10);
var tenth = time % 10;
if (min < 10) {
min = "0" + min;
}
if (sec <10) {
sec = "0" + sec;
} else if (sec>59) {
var sec;
}
document.getElementById("output").innerHTML = min + ":" + sec + ":0" + tenth;
timeIncrement();
},10);
}
} // end function timeIncrem
function formatNumber(n){
return n > 9 ? "" + n: "0" + n;
}
</script>
</head>
<body>
<h1>Stopwatch</h1>
<p id="output"></p>
<div id="controls">
<button type="button" id ="start" onclick="startWatch();">Start</button>
<button type="button" id ="reset" onclick="watchReset();">Reset</button>
</div>
</body>
</html>
Your code is totally weird!
First you're using document.getElementById() for non-existing elements: maybe they belong to your original code and your didn't posted it complete.
Then I don't understand your time-count method:
you make timeIncrement() to be launched every 10 ms: so time/10 gives you a number of milliseconds
but you compute min and sec as if it was a number of seconds!
From there, all is wrong...
Anyway IMO your could make all that simpler using the getMilliseconds() function of the Date object.
Try this:
document.getElementById("output").innerHTML = [
Math.floor(time/100/60 % 60),
Math.floor(time/100 % 60),
time % 100
].map(formatNumber).join(':')
var time = 0;
var started;
var run = 0;
function startWatch() {
if (run == 0) {
run = 1;
timeIncrement();
} else {
run = 0;
}
}
function watchReset() {
run = 0;
time = 0;
document.getElementById("output").innerHTML = "00:00:00";
}
function timeIncrement() {
if (run == 1) {
setTimeout(function () {
time++;
document.getElementById("output").innerHTML = [
Math.floor(time/100/60 % 60),
Math.floor(time/100 % 60),
time % 100
].map(formatNumber).join(':')
timeIncrement();
},10);
}
}
function formatNumber(n){
return (n < 10 ? "0" : "") + n;
}
startWatch()
<div id="output"></div>

Convert jQuery timer and redirect to work with minutes and seconds, rather than just seconds

I have found this lightweight and excellent timer and redirect script based on jQuery, created by the 'jQuery by Example' site. The script redirects the user after a set number of seconds:
HTML:
<h1>You will be redirect to actual page after <span id="spnSeconds">10000</span> seconds.</h1>
jQuery:
$(document).ready(function () {
window.setInterval(function () {
var iTimeRemaining = $("#spnSeconds").html();
iTimeRemaining = eval(iTimeRemaining);
if (iTimeRemaining == 0) {
location.href = "http://jquerybyexample.blogspot.com/";
} else {
$("#spnSeconds").html(iTimeRemaining - 1);
}
}, 1000);
});
Here's the fiddle: http://jsfiddle.net/jquerybyexample/2WmJb/
I am trying to modify it to work with minutes and seconds - would anyone know how to do this? I've tried simply modifying the HTML to 25:00 but this doesn't seem to be working (thought it wouldn't the that simple!).
Many thanks in advance for your help...
Best to use a data attribute for the time and display whatever you want as the text:
JSFiddle: http://jsfiddle.net/2WmJb/67/
You can access the data attribute with either .data('time') or .attr('data-time')
<h1>You will be redirect to actual page after <span id="spnSeconds" data-time="1500000">25 minutes</span></h1>
$(document).ready(function () {
window.setInterval(function () {
var iTimeRemaining = $("#spnSeconds").data('time');
iTimeRemaining = ~~iTimeRemaining;
if (iTimeRemaining == 0) {
location.href = "http://jquerybyexample.blogspot.com/";
} else {
var mins = ~~(iTimeRemaining / 60000);
$("#spnSeconds").html(mins + " minutes " + ~~(iTimeRemaining / 1000 % 60) + " seconds");
$("#spnSeconds").data('time', iTimeRemaining - 1000);
}
}, 1000);
});
Also Eval is Evil in most cases. Do a simple ~~ to coerce the value to an integer value, or use parseInt.
Changes Based on comment - add a pad function for leading zeroes
JSFiddle: http://jsfiddle.net/2WmJb/69/
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
$(document).ready(function () {
window.setInterval(function () {
var iTimeRemaining = $("#spnSeconds").data('time');
iTimeRemaining = ~~iTimeRemaining;
if (iTimeRemaining == 0) {
location.href = "http://jquerybyexample.blogspot.com/";
} else {
var mins = ~~(iTimeRemaining / 60000);
$("#spnSeconds").html(mins + ":" + pad(~~(iTimeRemaining / 1000 % 60),2));
$("#spnSeconds").data('time', iTimeRemaining - 1000);
}
}, 1000);
});
One final cleanup: http://jsfiddle.net/2WmJb/70/
Although not really significant when using jQuery id selectors (as they are very fast compared to say class selectors), you should reuse variables instead of repeatedly calling jQuery selectors. This example uses $span instead of $("#spnSeconds"). The $ prefix is a typical prefix for your variables that are jQuery objects (and more readable):
var $span = $("#spnSeconds");
var iTimeRemaining = $span.data('time');
iTimeRemaining = ~~iTimeRemaining;
if (iTimeRemaining == 0) {
location.href = "http://jquerybyexample.blogspot.com/";
} else {
$span.html(~~(iTimeRemaining / 60000) + ":" + pad(~~(iTimeRemaining / 1000 % 60),2));
$span.data('time', iTimeRemaining - 1000);
}

JS - confirmbox inside a function

I have a Javascript who works well, because yesterday i get here some very good solutions.
I want to know if i can extended this Javascript with another Query.
The query now, gives an alert when the number is bigger then 199. It works well.
But now i want to know, if i can get confirmbox inside for the same inputbox, when i write a number bigger then 100?
Here an example
I write the number 110 and i does get an confirm box with an Information(bla bla), and when i click Yes this number stays in the inputbox.
But when i write 200 or bigger then i does get the alert that this number is to big.
Here the code, what i get yesterday, whenn the number is bigger then 199:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Page</title>
<script type="text/javascript">
function minMax() {
var min = 0;
var mid = 99;
var max = 199;
var num = parseInt(document.getElementById('value_one').value);
if (num > mid && num < max) {
var r = confirm(num + ' n\'is greater than ' + mid+ '. Press Yes to retain it.');
if (r == false) document.getElementById('value_one').value = "";
return false;
}
if (min > num || max < num) {
alert(num + ' n\'is not between ' + min + ' and ' + max);
return false;
}
</script>
</head>
<body>
<form>
Value: <input type='text' id="value_one" onBlur="minMax();">
</form>
</body>
</html>
Is it possible and if somebody has an idea?
You can use confirm box for this instead of alert. Check the demo it on w3school.
Try this
<script type="text/javascript">
function minMax() {
var min = 0;
var mid = 100;
var max = 199;
var num = parseInt(document.getElementById('value_one').value);
if (num > mid && num < max) {
var r = confirm(num + ' n\'is greater than ' + mid+ '. Press Yes to retain it.');
if (r == false) document.getElementById('value_one').value = "";
return false;
}
if (min > num || max < num) {
alert(num + ' n\'is not between ' + min + ' and ' + max);
return false;
}
}
</script>
Check the demo on jsFiddle.net.
Hope this works out for you.
There is a confirm box you can control it based on the option you selected(yes or cancel).
You can also make the textbox clean when it cross the max (document.getElementById('value_one').value=0)

Categories