Display message after countdown - javascript

I have currently created a countdown timer using javascript. I want to display a message right after the countdown finishes. So, how do I display that text message if the countdown finishes?
$(function(){
var note = $('#note'),
ts = new Date(2012, 0, 1),
newYear = true;
if((new Date()) > ts){
// The new year is here! Count towards something else.
// Notice the *1000 at the end - time must be in milliseconds
ts = (new Date()).getTime() + 24*60*60*1000;
newYear = false;
}
$('#countdown').countdown({
timestamp : ts,
callback : function(days, hours, minutes, seconds){
var message = "";
message += hours + " jam ";
message += minutes + " minit" + " dan ";
message += seconds + " saat" + " lagi!";
note.html(message);
}
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<!-- Our CSS stylesheet file -->
<link rel="stylesheet" href="assets/css/styles.css" />
<link rel="stylesheet" href="assets/countdown/jquery.countdown.css" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div id="continer">
<p><span id="timer"></span></p>
</div>
<center><img class="title" src="title.svg"></center>
<img class="icon1" src="icon1.svg">
<img class="icon2" src="icon2.svg">
<div id="countdown"></div>
<p id="note"></p>
<!-- JavaScript includes -->
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="assets/countdown/jquery.countdown.js"></script>
<script src="assets/js/script.js"></script>
</body>
</html>
Below is the code that I used

Well you can use setInterval, clearInterval and use a counter to keep track of seconds passed
function myFunction() {
var seconds = 0;
var finiteNumber = 300; // any number which can be calculated
var interval = setInterval(function(){
seconds++;
if(seconds === finiteNumber) {
console.log(seconds);
clearInterval(interval )
}
}, 1000);
}

You should use setTimeout as it will automatically stop on one successful execution.
function myFunction() {
var myTimeInSeconds = 600;
setTimeout(function(){
console.log(seconds);
alert('Success');
document.getElementById("demo").innerHTML = "Success Message!";
}, myTimeInSeconds);
}

Related

CSS Stylesheet Switching via adding cookies

Code I'm using, works great but it doesn't stick when navigating around the site - because it needs to trigger a cookie - is there a way to do that? Here's the entire code I'm using:
<!DOCTYPE html>
<html>
<head>
<link id="pagestyle" rel="stylesheet" type="text/css" href="default.css">
<script>
function swapStyleSheet(sheet){
document.getElementById('pagestyle').setAttribute('href', sheet);
}
</script>
</head>
<body>
<h2>Javascript Change StyleSheet Without Page Reload</h2>
<button onclick="swapStyleSheet('dark.css')">Dark Style Sheet</button>
<button onclick="swapStyleSheet('blue.css')">Blue Style Sheet</button>
<button onclick="swapStyleSheet('default.css')">Default Style Sheet</button>
</body>
</html>
Nathaniel is correct in his comment that JS executes after the page is loaded, so you'll see a noticeable flicker if you apply the style after page load.
However, for the sake of answering your question, you can get/set a cookie with some pretty simple javascript.
function setCookie(name, value, days)
{
var d = new Date();
d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = name + "=" + value + "; expires=" + d.toUTCString() + "; path=/";
}
function getCookie(name)
{
var cookies = document.cookie.split(";");
for(var i = 0; i < cookies.length; i++)
{
var ck = cookies[i].trim().split("=");
if(ck[0] == name)
return ck[1];
}
return false;
}
Here's an example with your code:
window.onload = function(){
var viewmode = getCookie("viewmode");
if(viewmode)
document.getElementById('pagestyle').setAttribute('href', viewmode);
}
function swapStyleSheet(sheet){
document.getElementById('pagestyle').setAttribute('href', sheet);
setCookie("viewmode", sheet, 30);
}
function setCookie(name, value, days)
{
var d = new Date();
d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = name + "=" + value + "; expires=" + d.toUTCString() + "; path=/";
}
function getCookie(name)
{
var cookies = document.cookie.split(";");
for(var i = 0; i < cookies.length; i++)
{
var ck = cookies[i].trim().split("=");
if(ck[0] == name)
return ck[1];
}
return false;
}
<!DOCTYPE html>
<html>
<head>
<link id="pagestyle" rel="stylesheet" type="text/css" href="default.css">
</head>
<body>
<h2>Javascript Change StyleSheet Without Page Reload</h2>
<button onclick="swapStyleSheet('dark.css')">Dark Style Sheet</button>
<button onclick="swapStyleSheet('blue.css')">Blue Style Sheet</button>
<button onclick="swapStyleSheet('default.css')">Default Style Sheet</button>
</body>
</html>

Pushing and iterating over array to display history report?

I am building a project to help kids in school learn how to read faster. I have borrowed bits of code here and there and mixed up a timer and text generator.
Now I am trying to build a function to generate a summary of the latest reading time (so that they can see progress), perhaps in the form of <ol>, I guess I need to iterate over an array, push into it and then display but none of that seems to work.
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var ampm = "";
m = checkTime(m);
if (h > 12) {
h = h - 12;
ampm = " PM";
} else if (h == 12) {
h = 12;
ampm = " AM";
} else if (h < 12) {
ampm = " AM";
} else {
ampm = "PM";
};
if (h == 0) {
h = 12;
}
document.getElementById('display').innerHTML = h + ":" + m + ampm;
var t = setTimeout(function() {
startTime()
}, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
function startDate() {
var d = new Date();
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
document.getElementById("date").innerHTML = days[d.getDay()] + " | " + [d.getMonth() + 1] + "/" + d.getDate() + "/" + d.getFullYear();
}
var quotes = ["",
"\"Dude, suckin' at something is the first step at being sorta good at something.\"<br>- Jake <small><em>(Adventure Time)</em></small>",
"\"Either I will find a way, or I will make one.\"<br> - Philip Sidney",
"\"Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time.\"<br>- Thomas A. Edison",
"\"You are never too old to set another goal or to dream a new dream.\"<br>- C.S Lewis",
"\"If you can dream it, you can do it.\"<br>- Walt Disney",
"\"Never give up, for that is just the place and time that the tide will turn.\"<br>- Harriet Beecher Stowe",
"\"I know where I'm going and I know the truth, and I don't have to be what you want me to be. I'm free to be what I want.\"<br>- Muhammad Ali",
"\"If you always put limit on everything you do, physical or anything else. It will spread into your work and into your life. There are no limits. There are only plateaus, and you must not stay there, you must go beyond them.\"<br>- Bruce Lee",
];
function genQuote() {
var quote = document.getElementById("quote");
var generate = document.getElementById("gen");
generate.addEventListener("click", changeText);
quote.innerHTML = quotes[0];
function changeText() {
var searchTerm = quote.innerHTML;
var index = quotes.indexOf(searchTerm) + 1;
if (index == quotes.length) index = 0;
var result = quotes[index];
quote.innerHTML = result;
return;
}
}
var startTime, endTime;
function start() {
startTime = performance.now();
};
function end() {
endTime = performance.now();
var timeDiff = endTime - startTime;
timeDiff /= 1000;
var seconds = Math.round(timeDiff);
var minutes = Math.round(seconds / 60);
document.getElementById("quote").innerHTML = ("You have read for:" + " " + minutes + " minutes" + " " + seconds + " seconds");
setTimeout(function() {
location.reload();;
}, 5000);
}
function report() {
// results = [];
// times = document.getElementById("quote").innerHTML;
// for (i=0; i <= times.length; i++) {
// results.push(i);
// return results;
// }
}
<div id="display"></div>
<div id="date"></div>
<div id="quote"></div>
<div id="get"></div>
Here is the HTML in case that help:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<title>2 Cool 4 School</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<body onload="startTime(); startDate()">
<div class="container">
<div id="date"></div>
<div id="display"></div>
<div id="content">
<p id="quote">"the people who are crazy enough to think they can change the world are the ones who do." <br/>- Steve Jobs</p>
</div>
</div>
<div id="b-nav">
<ul>
<button id="genone"class="btn btn-outline-primary" onclick="start()">Start</button>
<button id="gen" onclick="genQuote()">Continue reading</button>
<button id="genthree" class="btn btn-outline-success" onclick="report()">History</button>
<button id="gentwo" class="btn btn-outline-secondary" onclick="end()">End</button>
</ul>
</div>
</body>
<script src="script.js"></script>
</html>
Right now when I click Stars the timer runs, when I click End after that I am provided "you have read for: 0 minutes 4 seconds"
I would like to get a report of this something like:
you have read for: 3 minutes 30 seconds
you have read for: 2 minutes 50 seconds
you have read for: 1 minutes 40 seconds
etc Hope that helps(sorry I didnt get the snippet thing)
the biggest problem is placing "return results;" inside your loop. which means your loop never fully executes. move that outside your loop.
secondly, your report() function is just going to return a string of numbers, [0,1,2,3,4...] which is probably not what you are looking for.

My clock won't work. Why isn't InnerHTML not updating?

Sorry if this topic is in the "annoying ones category". I recently tried to learn JS and I'm trying to make a simple clock to work. Nothing too fancy I'd say but the problem is that I can't update the values of my hours, minutes and seconds. I used .innerHTLM with a setInterval but it doesn't work. In Chrome's inspector it seems to try changing the datas but no... Any ideas guys ?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../css/style-clock.css">
<title>Clock</title>
</head>
<body>
<div class="container">
<div class="clock">
<span id="hours"></span>
<span id="mins"></span>
<span id="secs"></span>
</div>
</div>
<script src='../js/app-clock.js'></script>
</body>
</html>
JS:
const time = new Date();
function currentTime(){
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
document.getElementById("hours").innerHTML = hour;
document.getElementById("mins").innerHTML = minute;
document.getElementById("secs").innerHTML = second;
}
setInterval(currentTime,500);
You were close. Since you define time outside of the interval function, it only gets assigned once. Just move time into the currentTime() function like this:
function currentTime() {
const time = new Date();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
document.getElementById("hours").innerHTML = hour;
document.getElementById("mins").innerHTML = minute;
document.getElementById("secs").innerHTML = second;
}
setInterval(currentTime, 500);
<div class="container">
<div class="clock">
<span id="hours"></span>
<span id="mins"></span>
<span id="secs"></span>
</div>
</div>
You have decelerated outside of function that is called intervals.
CodePen Example
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../css/style-clock.css">
<title>Clock</title>
</head>
<body>
<div class="container">
<div class="clock">
<span id="hours"></span>
<span id="mins"></span>
<span id="secs"></span>
</div>
</div>
<script src='../js/app-clock.js'></script>
</body>
</html>
JS
setInterval(function(){
const time = new Date();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
document.getElementById("hours").innerHTML = hour;
document.getElementById("mins").innerHTML = minute;
document.getElementById("secs").innerHTML = second;
}, 500);
The problem seems to be the positioning of the const time.
The thing is, the output of Date() will be set to const time at the beginning of the script and the currentTime() function will keep on updating the same values over and over again. So, in your case, the values were actually getting updated but since they were the same values, you couldn't make the difference.
Solution: To make it work, you need to update the value of the const time every time you need to update the value of the innerHTML. You simply need to do the following change:
JS:
function currentTime(){
const time = new Date();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
document.getElementById("hours").innerHTML = hour;
document.getElementById("mins").innerHTML = minute;
document.getElementById("secs").innerHTML = second;
}
setInterval(currentTime,500);
Move the "new Date()" line into the function to set the time each interval to the current time.
function currentTime(){
const time = new Date();
var h = time.getHours();
var m = time.getMinutes();
var s = time.getSeconds();
document.getElementById("hours").innerHTML = h;
document.getElementById("mins").innerHTML = m;
document.getElementById("secs").innerHTML = s;
}
setInterval(currentTime,500);

Countdown with a delay in JavaScript

I've started to learn JavaScript, and I'm coding a program that get a number from the user and counts down to zero with a delay of one second for each number.
This is my code:
function DescreasNo(){
var MyInput = parseInt(document.getElementById('HoursOfWork').value);
var output = document.getElementById('output01');
output.innerHTML = '';
for ( var i=MyInput ; i>0 ; i--){
output.innerHTML += i +"<br>";
}
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="StyleSheet.css" />
<script src="Script.js"></script>
<title>EyeProctect Project</title>
</head>
<body>
<h1>Eye Protect</h1>
<h4>Keep Your Eyes safe</h4>
<input type="text" id="HoursOfWork" placeholder="Enter your hours of work ...." />
<button class="start" onclick="DescreasNo()" >Let's Go!</button>
<p id="output01"></p>
</body>
</html>
I used setTimeout and setInterval, but my problem is that it just shows zeros for each number, like this:
0, 0, 0, 0
Please help me to solve this problem.
You can use setTimeout() with IIFE:
function DescreasNo(){
var MyInput = parseInt(document.getElementById('HoursOfWork').value);
var output = document.getElementById('output01');
output.innerHTML = '';
(function loop (i) {
setTimeout(function () {
output.innerHTML += i +"<br>";
if (--i) loop(i); // call the function until end
}, 1000); // 1 second delay
})(MyInput);
}
<h1>Eye Protect</h1>
<h4>Keep Your Eyes safe</h4>
<input type="text" id="HoursOfWork" placeholder="Enter your hours of work ...." />
<button class="start" onclick="DescreasNo()" >Let's Go!</button>
<p id="output01"></p>
You're probably misunderstanding how to user a closure along with setTimeout (or setInterval).
function decreaseNumber() {
const total_hours = parseInt(document.getElementById('HoursOfWork').value);
const output_div = document.getElementById('output01');
let current_hour = total_hours;
const countdown = () => {
output_div.innerHTML += current_hour + "<br />";
if (--current_hour > 0) {
setTimeout(countdown, 1000); // 1000 milliseconds
}
};
countdown();
}
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="StyleSheet.css" />
<script src="Script.js"></script>
<title>EyeProctect Project</title>
</head>
<body>
<h1>Eye Protect</h1>
<h4>Keep Your Eyes safe</h4>
<input id="HoursOfWork" placeholder="Enter your hours of work ...." />
<button class="start" onclick="decreaseNumber()">Let's Go!</button>
<p id="output01"></p>
</body>
</html>
With setInterval you could do it like this.
function DescreasNo(){
var MyInput = parseInt(document.getElementById('HoursOfWork').value);
var output = document.getElementById('output01');
output.innerHTML = '';
var countDown = MyInput;
var intervalId = setInterval(function () {
output.innerHTML += countDown +"<br>";
if (--countDown <= 0)
clearInterval(intervalId); // clear timer when finished
}, 1000); // 1 second delay between decrements
}
<h1>Eye Protect</h1>
<h4>Keep Your Eyes safe</h4>
<input type="text" id="HoursOfWork" placeholder="Enter your hours of work ...." />
<button class="start" onclick="DescreasNo()" >Let's Go!</button>
<p id="output01"></p>
I would do this with a setInterval you can allow fractional hours if you use parseFloat instead of parseInt. You can also format the seconds fairly easily to give a nice readout.
You should be careful about clearing the interval too incase someone presses the button more than once during the countdown otherwise you will get multiple timers. Here if you press twice it resets it.
Some improvements would include validating input to make sure it's a number:
let int;
function DescreasNo() {
clearInterval(int) // clear interval to allow button to reset counter
var MyInput = document.getElementById('HoursOfWork').value;
let seconds = (parseFloat(MyInput) * 60 * 60)
var output = document.getElementById('output01');
int = setInterval(() => {
if (seconds <= 0) { // finished
clearInterval(int)
return
}
output.innerHTML = formatTime(seconds--)
}, 1000)
}
function formatTime(seconds) {
let hours = Math.floor(seconds / (60 * 60)).toString().padStart(2, '0')
let minutes = Math.floor((seconds - hours * 3600) / 60).toString().padStart(2, '0');
let second = Math.floor(seconds - (hours * 3600) - (minutes * 60)).toString().padStart(2, '0');
return `${hours}:${minutes}:${second}`;
}
<h1>Eye Protect</h1>
<h4>Keep Your Eyes safe</h4>
<input type="text" id="HoursOfWork" placeholder="Enter your hours of work ...." />
<button class="start" onclick="DescreasNo()">Let's Go!</button>
<p id="output01"></p>

How to disable a HTML submit button for a certain period of time everyday

I want to disable a button for a certain period of time everyday.
For ex: Let's say, html submit button gets disabled everyday between
11:00am and 4:00 pm.
<script type="text/javascript">
function checkButton() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
//Hide button at 11:00 AM
if(hours == 11 && minutes == 00) {
$("#btn").hide();
}
//Show button at 04:00 PM
if(hours == 16 && minutes == 00) {
$("#btn").show();
}
}
</script>
HTML submit button reference.
<body>
<input id="btn" type="submit" value="submit" onload="checkButton()">
</body>
You shouldn't check for equality but rather check for dates being between the mentioned hours using < and > operators.
To check time between 11:00am and 4:00 pm:
let min = hours*60 + minutes;
if(min > 11*60 && min < 16*60) {
$("#btn").hide();
}else {
$("#btn").show();
}
And to check this everyday, you should put the checkButton function in a loop, such as by using setInterval function. Such as: for checking every 1 minute:
setInterval(checkButton, 60000);
My solution without Jquery:
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id="btn">Click me</button>
<script>
window.onload = function() {
let btn = document.getElementById('btn');
function checkButton(){
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let min = hours*60 + minutes;
if(min > 11*60 && min < 16*60) {
//$("#btn").hide();
btn.style.display = 'none';
console.log('btn hide');
}else {
//$("#btn").show();
btn.style.display = 'block';
console.log('btn show');
}
}
setInterval(checkButton, 6000);
}
</script>
</body>
</html>
You currently just check for a point in time, but your description assumes you want to have a time range to be checked. Hence, try the following:
if(hour >= 11 && < 16) { $('#btn').hide() }
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
window.addEventListener("load", function(){
var currentTime = new Date();
var hours = currentTime.getHours();
var newButton = document.getElementById("btn");
if(hours >= 11 && hours <= 18) {
newButton.style.display = "none";
}
else {
newButton.style.display = "block";
}
}, false);
</script>
</head>
<body>
<div>Test</div>
<input type="submit" id="btn">
</body>
</html>
Use Php Date function to show the button between the hours.
<?php
$hour=date('H');
if(($hour <=11) || ($hour >=16)) {?>
<script type="text/javascript">
$("#button").show();
</script>
<?php }
?>

Categories