Javascript- How to reset button counter when timer reaches 0 - javascript

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);
}

Related

I have create Stopwatch and I want to display laps in my HTML page in 4 columns and 4 rows on lap button click

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.

onclick="window.open() is not working for multiple URLs

var minutes = 0;
var seconds = 3;
url = 'https://www.google.com';
url2 = 'https://www.yahoo.com';
link_name = '<div class="j">Download File</div>'
var timer = setInterval(function () { myCounter() }, 1000);
function myCounter() {
if (minutes > 59 || minutes < 0) {
document.getElementById("time").innerHTML = "<font color='red'>Please check the minutes variable, Set it in between 0 to 59</font>";
} else {
seconds--;
if (seconds == 0) {
minutes = minutes - 1;
seconds = 60;
}
document.getElementById("time").innerHTML = minutes + " Minutes " + seconds + " Seconds";
if (minutes == -1) {
clearTimeout(timer);
document.getElementById("time").innerHTML = "<h3>Tile</h3>";
document.getElementById("data").innerHTML = "<a href='" + url + "' onclick='window.open(" + url2 + ")'>" + link_name + "</a>";
}
}
}
Hey guys I want to visit google.com in home tab and yahoo.com in new tab if click on "Download File". Don't worry about this Countdown javascript. Just I want to fix this phrase. document.getElementById("data").innerHTML="<a href='"+url+"' onclick='window.open("+url2+")'>"+link_name+"</a>"; I tried many times but I could only visit for google.com only. Please help me.
You can use a function that allows you to open two sites at the same time. By default what you want. Otherwise if you want to open in different tabs you have to put true for the third parameter.
// -- Function to visit two sites
function multi(url1, url2, twoTabs = false) {
if(twoTabs) {
window.open(url1);
} else {
window.location.href = url1;
}
window.open(url2);
}
// -- -- --
Now normally it should work. I added the missing minute.
// -- Function to visit two sites
function multi(url1, url2, twoTabs = false) {
if(twoTabs) {
window.open(url1);
} else {
window.location.href = url1;
}
window.open(url2);
}
// -- -- --
var seconds = 3;
var minutes = 0;
url = 'https://www.google.com';
url2 = 'https://www.yahoo.com';
link_name = '<div class="j">Download File</div>'
var timer = setInterval(function () {
myCounter()
}, 1000);
function myCounter() {
if (minutes > 59 || minutes < 0) {
document.getElementById("time").innerHTML = "<font color='red'>Please check the minutes variable, Set it in between 0 to 59</font>";
} else {
seconds--;
if (seconds == 0) {
minutes = minutes - 1;
seconds = 60;
}
document.getElementById("time").innerHTML = minutes + " Minutes " + seconds + " Seconds";
if (minutes == -1) {
clearTimeout(timer);
document.getElementById("time").innerHTML = "<h3>Tile</h3>";
/* document.getElementById("data").innerHTML = "<a href='" + url + "' onclick='window.open(" + url2 + ")'>" + link_name + "</a>";*/
document.getElementById("data").innerHTML = '<div onclick="multi(url, url2)">Clic</div>\n';
}
}
}
No need if conditions. Simply..
// -- Function to visit two sites
function multi(url1, url2) {
window.open(url2);
window.location.href = url1;
}
document.getElementById("data").innerHTML = '<a onclick="multi(url, url2)">cLICK</a>\n';
Now it's 1000% working proof!!! Thank you so much Mister Henrique Rodrigues!

Javascript box that takes answer and updates

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>

JS Code Works in jsbin and Not in jsfiddle or Chrome/Safari?

I am trying to figure out why this code is working only in jsbin and not in jsfiddle or in any web browser as an html/js file. I have tried debugging but cannot find a conclusion.
I made the mistake of coding directly in jsbin instead of a document. Any input would be appreciated.
http://jsbin.com/tuduxedohe/7/edit
http://jsfiddle.net/2rs1x5pz/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Timer</title>
<script type="text/javascript" src="part2.js"></script>
</head>
<body>
<h1><div id="time">00:00:00</div></h1>
<div id="result"></div>
<button id="start" onclick ="startClock();" >Start</button>
<button id="stop" onclick="stopTimer();">Stop</button>
<button id="clear" onclick="resetTimer();">Reset</button>
</body>
</html>
var currentTime = document.getElementById('time');
var hundreths = 0;
var seconds = 0;
var minutes = 0;
var t;
function startClock() {
function add() {
hundreths++;
if (hundreths > 99) {
hundreths = 0;
seconds++;
if (seconds > 59) {
seconds = 0;
minutes++;
}
if(minutes >= 10) {
seconds= 0;
minutes= 0;
stopTimer();
}
}
if (hundreths > 9 && seconds < 9) {
currentTime.innerHTML = "0" + minutes + ":" + "0" + seconds + ":" + hundreths;
}
else if ((seconds > 9 ) && (hundreths < 9)) {
currentTime.innerHTML = "0" + minutes + ":" + seconds + ":" + "0" + hundreths;
}
else if((seconds > 9) && (hundreths > 9)) {
currentTime.innerHTML = "0" + minutes + ":" + seconds + ":" + hundreths;
}
else if ((minutes > 9) && (seconds < 9) && (hundreths < 9)) {
currentTime.innerHTML = minutes + ":" + "0" + seconds + ":" + "0" + hundreths;
}
else if ((minutes > 9) && (seconds > 9) && (hundreths < 9)) {
currentTime.innerHTML = minutes + ":" + seconds + ":" + "0" + hundreths;
}
else if ((minutes > 9) && (seconds > 9) && (hundreths < 9)) {
currentTime.innerHTML = minutes + ":" + seconds + ":" + hundreths;
}
else {
currentTime.innerHTML = "0" + minutes + ":" + "0" + seconds + ":" + "0" + hundreths;
}
timer();
}
function timer() {
t = setTimeout(add, 1);
}
timer();
} // end function start clock
function stopTimer() {
document.getElementById("result").innerHTML = "<p>" + ("Your time is: " + minutes + " minutes, " + seconds + " seconds, " + "and " + hundreths + " hundreths") + "</p>";
clearTimeout(t);
}
function resetTimer() {
hundreths = 0;
seconds = 0;
minutes = 0;
currentTime.innerHTML = "00:00:00";
}
That is because by default the script is added in a onload handler in jsfiddle, so your methods is available only inside the scope of that closure. So it will be
window.onload=function(){
//your script is here
}
You are trying to access them in global scope when you are trying to call them from on<event>="" attributes which will give an error like Uncaught ReferenceError: startClock is not defined in your console.
Change the second dropdown in the left panel under Frameworks & Extensions to body/head in the left panel of fiddle to add the script without a wrapper function
Demo: Fiddle

Assigning value for a control which is in child page

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;

Categories