I have created a countdown timer function in javascript and the body tag onload event I am calling this function. But my problem is I want to display the time left thing in a label which is Child page. Is there a way to assign a control which is in child page from master page ?
Here is the function
<script type="text/javascript">
var tim;
var min = 2;
var sec = 0;
function Timer() {
if (min == 0 && sec == 0) {
clearTimeout(tim);
window.location.href = "Result.aspx";
}
else {
if (sec < 1) {
sec = 59;
if (min > 0)
min = min - 1;
}
else
sec = sec - 1;
var mins = "", secs = "";
if (min <= 9)
mins = "0" + min;
else
mins = min;
if (sec <= 9)
secs = "0" + sec;
else
secs = sec;
document.getElementById("lblTimer1").innerHTML = "Time Left : " + mins + " : " + secs;
tim = setTimeout("Timer()", 1000);
}
}
</script>
I'm calling Timer() in body onload event and lblTimer1 is the label control which is in child page.
Thanks,
Nuthan Gowda
If you are sure you won't run into conflicting ids, depending on your framework version, most simple way is setting ClientIDMode="Static" on your label. Your code should then work.
If not sure, you may set a (unique) utility cssclass of 'timerLabel' on your label, then in your function :
document.getElementsByClassName("timerLabel")[0].innerHTML = "Time Left : " + mins + " : " + secs;
Related
I have created a stopwatch and I want to display laps in my HTML page on lap button click but in 4 columns.
Here is my complete code: https://jsfiddle.net/waqasumer/agru2bdL/
Index.html
<div class="row" id="laps">
</div>
Js
var min = 0;
var sec = 0;
var msec = 0;
var getMin = document.getElementById("min");
var getSec = document.getElementById("sec");
var getmsec = document.getElementById("msec");
var interval;
function timer() {
msec++
getmsec.innerHTML = msec;
if (msec >= 100) {
sec++;
if (sec <= 9) {
getSec.innerHTML = "0" + sec;
} else {
getSec.innerHTML = sec;
}
msec = 0;
} else if (sec >= 60) {
min++;
if (min <= 9) {
getMin.innerHTML = "0" + min;
} else {
getMin.innerHTML = min;
}
sec = 0;
}
}
function lapTimer() {
var Laps = document.getElementById('laps');
Laps.innerHTML += "<div>" + " " + getMin.innerHTML + ":" + getSec.innerHTML + ":" + getmsec.innerHTML + "</div>";
}
ยดยดยด
I believe this is a typical solution:
#laps > div {
width: 25%;
float: left;
}
This will lay out the laps in 4 columns, then repeat onto a new line once those 4 columns are populated.
If I understood this requirement correctly.
I'm trying to get a simple click counter function to countdown the number of clicks users are left to use, where the number of clicks left will reset every 24 hours.
I've look through a few tutorials and implemented it visually in the alert once user has maxed the click. But how do I get about only resetting the count once the timer reaches 0.
HTML
<p><button onclick="clickCounter()" type="button">Click</button></p>
<div id="result"></div>
JavaScript
function clickCounter() {
var d = new Date();
var hours = 24 - d.getHours();
var min = 60 - d.getMinutes();
if((min + '').length == 1){
min = '0' + min;
}
var sec = 60 - d.getSeconds();
if((sec + '').length == 1){
sec = '0' + sec;
}
if(typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
if(Number(localStorage.clickcount) <= 0){
alert('You have max the number of connect \nTime left: '+ hours+':'+min+':'+sec);
localStorage.clickcount =4;
}
localStorage.clickcount = Number(localStorage.clickcount)-1
}
else
{
localStorage.clickcount = 4;
}
document.getElementById("result").innerHTML = "You have " + localStorage.clickcount + " clicks left.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
Here's a sample of how it's running. Currently I've set it to reset right after the alert pops out, and I'm just figuring how to reset automatically when the timer is up. Thanks for any feedback and help
sample link
You can set an interval function to check the time and reset values when time is up. I've changed your code to add a interval function
checkClickCount();
function clickCounter() {
var d = new Date();
var hours = 24 - d.getHours();
var min = 60 - d.getMinutes();
if ((min + '').length == 1) {
min = '0' + min;
}
var sec = 60 - d.getSeconds();
if ((sec + '').length == 1) {
sec = '0' + sec;
}
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
if (Number(localStorage.clickcount) < 1) {
alert('You have max the number of connect \nTime left: ' + hours + ':' + min + ':' + sec);
return;
}
localStorage.clickcount = Number(localStorage.clickcount) - 1
} else {
localStorage.clickcount = 4;
}
document.getElementById("result").innerHTML = "You have " + localStorage.clickcount + " clicks left.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
var intv = null;
function checkClickCount(){
// interval run a function in a specified period of time
intv = window.setInterval(function(){
var currentTime = new Date();
var remainDateTime = new Date();
remainDateTime.setHours(24 - currentTime.getHours());
remainDateTime.setMinutes(60 - currentTime.getMinutes());
remainDateTime.setSeconds(60 - currentTime.getSeconds());
if(localStorage.clickcount > 1){
return;
}
// If the remaining times finished, the click count will be reset
if(remainDateTime.getHours() + remainDateTime.getMinutes() + remainDateTime.getSeconds() == 0){
localStorage.clickcount = 4;
document.getElementById("result").innerHTML = "You have " + localStorage.clickcount + " clicks";
return;
}
document.getElementById("result").innerHTML = "You will get 4 more clicks in " + remainDateTime.getHours() + ":" + remainDateTime.getMinutes() + ":" + remainDateTime.getSeconds() + " later.";
}, 1000);
}
I've gone over this for hours trying different things and can't get it to work, I've made a dice that rolls every 10 seconds, the timer and the dice roll shows on screen and constantly updates the roll. I want to make a box that shows the previous 5 rolls of the dice and constantly updates. Not sure if I have to make separate function or add it to my existing function. Here is what I have so far.
<script type = "text/javascript">
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
}
function tick( ) {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else {
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1;
die1.innerHTML = d1;
status.innerHTML = "Dice Roll "+diceTotal+".";
clearInterval(ticker);
startTimer(0000010); // start again
}
var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
}
startTimer(0000010);
</script>
One option would be to have 5 predefined divs and have them cleared/filled dynamically.
Another option is to keep the roll history in an array and fill the 'history element' from that array.
For example:
rolls.push(d1); //add roll to history
if(rolls.length > maxrollhistory)
rolls.shift();
die1.innerHTML = 'Previous rolls: ' + rolls.reduce(function(prev,cur){return '<span class="rollhistory">' + cur + ' </span>' + prev; }, '');
where rolls is the array containing the history. (rollhistory is a class I made up to format the results).
In the underlying example I took the liberty of restructuring the program to display the above (click here for fiddle ) :
var die1 = document.getElementById("die1"),
status = document.getElementById("status");
function startTimer(secs) {
var timeInSecs = parseInt(secs),
rolls = [],
rem = 0,
maxrollhistory = 5,
roll = function(){
var d1 = Math.floor(Math.random() * 6) + 1;
rolls.push(d1); //add roll to history
if(rolls.length > maxrollhistory)
rolls.shift();
die1.innerHTML = 'Previous rolls: ' + rolls.reduce(function(prev,cur){return '<span class="rollhistory">' + cur + ' </span>' + prev; }, '');
status.innerHTML = "Dice Roll "+ d1 +".";
},
tick = function(){
if (--rem <= 0) {
rem = timeInSecs;
roll();
}
var secs = rem;
var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
setTimeout(tick,1000);
}
tick();
}
startTimer(10);
All you need is to append. Check the snippet added status.innerHTML += "Dice Roll "+diceTotal+".<br>";
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
}
function tick( ) {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else {
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1;
die1.innerHTML = d1;
status.innerHTML = "Dice Roll "+diceTotal+".<br>" +status.innerHTML;
clearInterval(ticker);
startTimer(0000010); // start again
}
var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
}
startTimer(0000010);
<div id="countdown"></div> <div id="die1" class="dice">0</div> <h2 id="status" style="clear:centre;"></h2>
i have made a simple music player and there is 2 events for it one for updating elapsed time and another for durationchange...elapsed time's function works fine but total time function doesn't...i have looked up in http://www.w3schools.com/tags/ref_av_dom.asp and durationchange is a standard event but i don't get it why it doesn't work. i also thought maybe the reason is that script is defined before label elements but moving scripts to the end of file didn't worked either.
here is my code:
<!DOCType HTML>
<html>
<head>
<link rel="stylesheet" href="style.css"/>
<script type="text/JavaScript">
var audio = document.createElement("audio");
audio.id = "audio1"
audio.src = "Music.mp3";
audio.autoplay = true;
window.onload = function () {
audio.addEventListener('timeupdate', UpdateTheTime, false);
audio.addEventListener('durationchange', SetTotal, false);
}
function UpdateTheTime() {
var sec = audio.currentTime;
var min = Math.floor(sec / 60);
sec = Math.floor(sec % 60);
if (sec.toString().length < 2) sec = "0" + sec;
if (min.toString().length < 2) min = "0" + min;
document.getElementById('Elapsed').innerHTML = min + ":" + sec;
}
function SetTotal() {
var sec = audio.duration;
var min = Math.floor(sec / 60);
sec = Math.floor(sec % 60);
if (sec.toString().length < 2) sec = "0" + sec;
if (min.toString().length < 2) min = "0" + min;
document.getElementById('Total').innerHTML = "/ " + min + " : " + sec;
}
</script>
</head>
<body>
<form action="/" id="player">
<img src="Cover.jpg"/>
<label id="Title">
Imaginaerum
</label>
<label id="Artist">
Nightwish
</label>
<label id="Elapsed">--:--</label>
<label id="Total">/--:--</label>
</form>
</body>
</html>
In your case durationchange event fired before window.onload
var audio;
window.onload = function () {
audio= document.createElement("audio");
audio.id = "audio1"
audio.src = "Music.mp3";
audio.autoplay = true;
audio.addEventListener('timeupdate', UpdateTheTime, false);
audio.addEventListener('durationchange', SetTotal, false);
}
function UpdateTheTime() {
var sec = audio.currentTime;
var min = Math.floor(sec / 60);
sec = Math.floor(sec % 60);
if (sec.toString().length < 2) sec = "0" + sec;
if (min.toString().length < 2) min = "0" + min;
document.getElementById('Elapsed').innerHTML = min + ":" + sec;
}
function SetTotal() {
var sec = audio.duration;
var min = Math.floor(sec / 60);
sec = Math.floor(sec % 60);
if (sec.toString().length < 2) sec = "0" + sec;
if (min.toString().length < 2) min = "0" + min;
document.getElementById('Total').innerHTML = "/ " + min + " : " + sec;
}
Example http://jsfiddle.net/rU7SU/
I asked yesterday about saving a timer value when the browser closes and then start counting again when the user opens it. I've found that using cookies must be a good solution, so i've added the set and getcookie functions, but still i can't get my timer values. This might be easy, but i cant see what's wrong because i'm still too noob in javascript.
Does someone know what i'm doing wrong?
thank you!!
here's the code i have so far:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head>
<title>Test</title>
<script type="text/javascript">
var sec = 0;
var min = 0;
var hr = 0;
var dias = 0;
var bool = true;
function stopwatch() {
sec++;
if (sec == 60) {
sec = 0;
min += 1;
}
if (min == 60) {
min = 0;
hr += 1;
}
if (hr == 24) {
hr = 0;
dias += 1;
}
totalTime = ((dias<=9) ? "0" + dias : dias) + "d, " + ((hr<=9) ? "0" + hr : hr) + " : " + ((min<=9) ? "0" + min : min) + " : " + ((sec<=9) ? "0" + sec : sec);
document.getElementById("timer").innerHTML = totalTime;
if (bool == true) {
start = setTimeout("stopwatch()", 1000);
}
}
function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}
function getCookie (name) {
var cname = name + "=";
var dc = document.cookie;
if (dc.length > 0) {
begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end));
}
}
return null;
}
var exp = new Date();
exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30));
</script>
</head>
<body onload="stopwatch()">
<div id="timer" name="timer"> </div>
<button onclick="bool = false"; > pause </button>
<button onclick="bool = true;stopwatch();" > resume </button>
<form>
<input type="button" value="Set a Cookie" onClick="setCookie('myCookie',timer.value, exp)">
</form>
<form>
<input type="button" value="Get Cookie Value" onClick="this.form.tf.value = getCookie('myCookie')">
<input type="text" name="tf" size="30">
</form>
</body>
</html>
Firstly, few issues with your code:
Strings shouldn't be used in setTimeouts
Your variables should be initialised as integers, not strings.
Back to your problem, use the unload event to save a cookie with the current time when the user closes the page. Then when the user opens the page again, detect the cookie and continue from where you left off.
If you can't figure out how to pause it, what about getting the Date when the browser closes and then getting the date when it opens again. Calculate the difference and subtract it from the value your timer is at.
I'm just throwing a general idea out there! :D