How to show text only at specified times - javascript

I want to make some text visible between 3pm and 6pm and invisible otherwise.
THNX! IT WORKS!

This solution uses jQuery:
var timeout = setTimeout(TimeCheck, 1000);
function TimeCheck() {
var d = new Date();
var h = d.getHours();
if(h>=15 && h<18) {
$('#message').show();
}
else
$('#message').hide();
clearTimeout(timeout);
timeout = setTimeout(TimeCheck, 1000);
}
You can increase the timeout frequency.
Updated based on comment
<html>
<head>
<script>
var timeout = setTimeout(TimeCheck, 1000);
function TimeCheck() {
var d = new Date();
var h = d.getHours();
if(h>=15 && h<=18) {
document.getElementById('message').style.display = 'block';
}
else
document.getElementById('message').style.display = 'none';
setTimeout(TimeCheck, 1000);
}
</script>
</head>
<body>
<p id="message" style="display:none;"> Hoi </p>
</body>
</html>

var d = new Date(); // for now
var h=d.getHours();
if(h>=15 && h<18){
}
else{
document.getElementById(id).style.display = 'block';
}
"id" is the id of your text from html you want to hide.
You can understand why it is h<18. Because, 18:20 has a hour value of 18. But, You need it between 15 and 18.

Related

Show Date.getTime() javascript into html

I am trying to make a stopwatch using html and javascript on my website.
Here is what I tried:
<!DOCTYPE HTML>
<html>
<script>
Date.setTime(0);
</script>
<body>
<p>Time: <script>document.write(Date.getTime());</script></p>
</body>
</html>
I want it to show milliseconds since load. I'm doing it on KhanAcademy. Does anybody know how to do this?
Also, somewhat, weirdly, there are no errors
If you want to show the milliseconds since the page load you need to update it using setInterval()
<!DOCTYPE HTML>
<html>
<body>
<p>Time: <span id="msec"></span> </p>
</body>
<script>
var msec = 0;
msec = setInterval(function(){
msec = msec + 1;
document.getElementById("msec").innerText = msec;
},1)
</script>
</html>
You likely meant to do this
NOTE the script tags have to be AFTER the span - it needs to exist.
let d = new Date();
d.setTime(1000)
const span = document.getElementById("time");
const tId = setInterval(function() {
if (d.getTime() <= 0) clearInterval(tId);
span.textContent = d.getTime();
d.setTime(d.getTime() - 10)
}, 10);
<span id="time"></span>
but that is the same as doing this
let d = 1000;
const span = document.getElementById("time");
const tId = setInterval(function() {
span.textContent = d-=10
if (d <= 0) clearInterval(tId);
}, 10)
<span id="time"></span>
Using the window load event so the script can stay in the head
Herre I am counting up
window.addEventListener("load", function() { // on page load
let d = 0;
const span = document.getElementById("time");
const tId = setInterval(function() {
span.textContent = d += 10
if (d >= 1000) clearInterval(tId);
}, 10);
});
<span id="time"></span>
You have to set an interval to update calculate the duration since starting the website (I choose 1 ms). The script has to be written in the code after the HTML-element is declared.
var start = performance.now();
setInterval(function() {
let time = performance.now();
document.getElementById('duration').innerHTML = 'Dauer: ' + (time - start) + ' ms.';
}, 1);
<div id='duration'></div>

onclick fires with no issues but addEventListener requires multiple clicks to work

I've tried this a few different ways. I'm attempting to create an event for a button that toggles an elements visibility on and off. for some reason when I use .onclick it works fine. Each time I click the button it toggles the element visibility as expected. However when I attempt to swap .onClick for addEventListener the button has to be clicked multiple times for it to work. It seems intermittent. It may work on the 1st click one time and then the next time it may require 2 or 3.
function showTime() {
options = {weekday: 'short', year: 'numeric', month: 'short', day: '2-digit'}
var date = new Date();
var hr = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
var period = "am";
if(hr == 0){
hr = 12;
}
if(hr > 12){
hr = hr - 12;
period = "pm";
}
min = (min < 10) ? "0" + min : min;
sec = (sec < 10) ? "0" + sec : sec;
var time = hr + ":" + min + ":" + sec + " " + period;
document.getElementById("displayTime").innerHTML = time;
document.getElementById("displayDate").innerHTML = date.toLocaleDateString("en-US", options);
var startTime = setTimeout(showTime, 1000);
//Set Alarm
var set = document.getElementById("setButton");
set.onclick = function(){
var timeVis = document.getElementById("displayTime");
if (timeVis.style.display !== 'none') {
timeVis.style.display = 'none';
} else {
timeVis.style.display = 'block';
}
}
}
showTime();
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="utf-8"/>
<title> Clock </title>
</head>
<body>
<div id="displayTime" onLoad="showTime()" ></div>
<input type="text" id="setInput">
<button id="setButton">set</button>
<div id="displayDate"></div>
<script src="DigitalClock.js"></script>
</body>
</html>
Below are the two alternate ways I attempted to use add an event listener
var set = document.getElementById("setButton");
set.addEventListener('click', function(){
var timeVis = document.getElementById("displayTime");
if (timeVis.style.display !== 'none') {
timeVis.style.display = 'none';
} else {
timeVis.style.display = 'block';
}
});
var set = document.getElementById("setButton");
var timeVis = document.getElementById("displayTime");
function vis(){
if (timeVis.style.display !== 'none') {
timeVis.style.display = 'none';
} else {
timeVis.style.display = 'block';
}
};
timeVis.addEventListener('click', vis);
The problem is that you use addEventListener inside the showTime() function, so each time showTime() is executed, you bind a new listener.
Now because of this:
var startTime = setTimeout(showTime, 1000);
The function is executed each second. As a result, after a couple of seconds, when you click one time on the button, the toggle part is executed multiple times.
On the other hand, with set.onclick, you only redefine the onclick property of the element, this is why it's working as expected.

how to add to an HTML time element

How can I use javascript to add to an existing HTML Time element. I have an html time element and want to be able to press a button that adds one minute to the current time. I don't want to use input type time. This is my existing code:
<body>
<time id = 'time'> 10:00 </time>
<button onclick = "addTime();">addTime</button>
<script>
function addTime(){
document.getElementById('time').innerHTML += '01:00'
}
</script>
</body>
but this just appends the time as a string. Is there an easy way to fix this?
You can use Date.prototype.setMinutes() with first two numbers of .innerHTML of element, Date.prototype.setSeconds() with parameter 0
<body>
<time id='time'> 10:00 </time>
<button onclick="addTime();">addTime</button>
<script>
const time = document.getElementById('time')
let date = new Date();
function addTime() {
date.setMinutes(1 + +time.innerHTML.match(/\d{2}/)[0]);
date.setSeconds(0);
time.innerHTML = String(date).slice(19, 24);
}
</script>
</body>
In html you can put this code:
<time id='time'> <label id="hour">10</label>:<label id="second">00</label> </time>
<button onclick="addTime();">addTime</button>
You can run this function:
function addTime() {
var h = parseInt(document.getElementById('hour').innerHTML);
var s = parseInt(document.getElementById('second').innerHTML);
s++;
var add = "0";
if (s < 10) {
add = "0" + s;
}
else {
add = s;
}
if (s == 60) {
add = "00";
h = h + 1;
}
if (h == 25) {
h = 1;
}
document.getElementById('hour').innerHTML = h;
document.getElementById('second').innerHTML = add;
}

digital calculator in Javascript and document.getElementsByClassName("DigitalCalculator")

I am trying to write a program for digital calculator.
My browser doesnt display any clock when I load the page.
<html>
<head>
<style type="text/css">
.DigitalCalculator{
background-color:blue;}
</style>
</head>
<body>
<div **class="DigitalCalculator"**></div>
<script type="text/javascript">
function updateTimer(){
var time = new Date();
var h = time.getHours();
var m = time.getMinutes();
var s = time.getSeconds();
var setTime = ;
setTime.innerHTML = **document.getElementsByClassName("DigitalCalculator")**;
setTimeout('updateTimer()',1000);
}
updateTimer();
</script>
</body>
</html>
Why does this dont work? document.getElementsByClassName("DigitalCalculator") ?
I resolved the problem by changing the code
and
var setTime = document.getElementById("clockDisplay");
Why cant I use the former document.getElementsByClassName("DigitalCalculator") ?
Please see my below program.
.DigitalCalculator{
background-color:blue;}
</style>
</head>
<body>
<div id = "DisplayClock" **class="DigitalCalculator"**></div>
<script type="text/javascript">
function updateTimer(){
var time = new Date();
var h = time.getHours();
var m = time.getMinutes();
var s = time.getSeconds();
var setTime =document.getElementById("DisplayClock");
setTime.innerHTML = h;
setTimeout('updateTimer()',1000);
}
updateTimer();
</script>
</body>
</html>
Compare your two versions:
// syntax error
var setTime = ;
// trying to set the innerHTML of ? to a list of elements
// makes no sense!
setTime.innerHTML = document.getElementsByClassName("DigitalCalculator");
versus:
// grab the div and keep it in a variable
var setTime =document.getElementById("DisplayClock");
// set the innerHTML of the div to the value of h (a number)
// now it makes sense...
setTime.innerHTML = h;
Also, I would recommend passing a function reference to setTimeout, instead of a string:
setTimeout(updateTimer, 1000);
Not sure of the advantage of using getElementsById(). However, this returns an array, so you either have to reference the first hit (as per example below) or enumerate the returned instances and update each one.
<html>
<head>
<style type="text/css">
.DigitalCalculator { background-color:blue; }
</style>
</head>
<body>
<div class="DigitalCalculator"></div>
<script type="text/javascript">
function updateTimer(){
var time = new Date();
var h = time.getHours();
var m = time.getMinutes();
var s = time.getSeconds();
var setTime = null;
setTime = document.getElementsByClassName('DigitalCalculator');
if ( setTime != null ) {
setTime[0].innerHTML = h.toString() + ':' + m.toString() + ':' + s.toString();
}
setTimeout('updateTimer()',1000);
}
updateTimer();
</script>
</body>
</html>

Forcing page refresh at a specific time with timezone

I'm trying to force a page to refresh with js at a specific time, after digging around I found the script below. However, it doesn't appear to take into consideration timezones. How would I implement that?
<html>
<head>
<title></title>
<script type="text/javascript">
function refreshAt(hours, minutes, seconds) {
var now = new Date();
var then = new Date();
if(now.getHours() > hours ||
(now.getHours() == hours && now.getMinutes() > minutes) ||
now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
then.setDate(now.getDate() + 1);
}
then.setHours(hours);
then.setMinutes(minutes);
then.setSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
refreshAt(15,06,0); //Will refresh the page at 3:06pm
</script>
</head>
<body onLoad="setInterval('getCurrentTime()', 1000);">
<div id="time"></div>
content
</body>
</html>
Here you go, reload will occur for every user exactly as you define in global vars in script:
EDIT!!! I had bug in code so I have updated the script...
EDIT working example:
http://simplestudio.rs/yard/tinediffredir/content.html
<html>
<head>
<title>Chk diff and reload if match</title>
<script>
var reload_time = "15060"; // this is 15:06:00 - change to desired reload time
var reload_hour_diff = 15; // for cheking diff - change to desired hours
var reload_minute_diff = 6; // for cheking diff - change to desired minutes
var time_zone_offset = "-5"; // globally looking from GMT time, change this according to DST
var reload_time_checker = setInterval(function(){reload_page()},300);
var diff = null;
function chk_reload_moment(offset) {
dat = new Date();
utc = dat.getTime() + (dat.getTimezoneOffset() * 60000);
default_date = new Date(utc + (3600000*offset));
var default_year = default_date.getFullYear();
var default_month = default_date.getMonth();
var default_day = default_date.getDate();
var default_hour = default_date.getHours();
var default_minutes = default_date.getMinutes();
var default_seconds = default_date.getSeconds();
user_date = new Date();
var user_year = user_date.getFullYear();
var user_month = user_date.getMonth();
var user_day = user_date.getDate();
var user_hour = user_date.getHours();
var user_minutes = user_date.getMinutes();
var user_seconds = user_date.getSeconds();
user_current = user_hour+""+user_minutes+""+user_seconds;
default_current_f = default_day+"/"+default_month+"/"+default_year+" "+default_hour+":"+default_minutes+":"+default_seconds;
user_current_f = user_day+"/"+user_month+"/"+user_year+" "+user_hour+":"+user_minutes+":"+user_seconds;
var timeEnd = new Date(user_current_f);
var timeEndH = timeEnd.getHours();
var timeEndM = timeEnd.getMinutes();
var new_reload_minute_diff = 60+reload_minute_diff;
diff = (timeEndH - reload_hour_diff + 12) + " hours " + (new_reload_minute_diff - timeEndM) + " minutes";
if (user_current == reload_time) {
return true;
}
else {
return false;
}
}
function reload_page() {
var chktime = chk_reload_moment(time_zone_offset);
if (chktime) {
window.location.reload();
}
else {
var timer_div = document.getElementById('timer');
timer_div.innerHTML = "remaining: " + diff + " until new content";
}
}
</script>
</head>
<body>
<div id="timer">
</div>
</body>
</html>
I think it is clear how to configure it but if you have some problems feel free to ask...

Categories