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

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>

Related

how to add animation in string

I want add rotation in my string for that i have set interval but its not getting me as i want. it works only for one time when i reload the browser. So what should i add for continuing the function.
this is my code
HTML
<html>
<head>
<title>JavaScript basic animation</title>
<script type="text/javascript">
</script>
<script type="text/javascript" src="myfunction_2.js"></script>
</head> <body onload="shubham()">
<div id="target">w3resource</div>
<button >click</button>
</body>
</html>
javascript
function shubham()
{
var x=document.getElementById('target').textContent;
var y=x.split('');
var z=y[0];
var m=y[y.length-1];
setInterval(function ()
{
document.getElementById('target').innerHTML = m+x.substring(0,8);
},500);
}
The problem with your code was that the variables were initialized once, and whenever, the setInterval function was called, there was no change in variables and hence the result remained the same which appeared as function only executed 1 time only.
Move your variables inside the setInterval function.
setInterval(function() {
var x = document.getElementById('target').textContent;
var y = x.split('');
var z = y[0];
var m = y[y.length - 1];
document.getElementById('target').innerHTML = m + x.substring(0, 8);
}, 500);
<div id="target">w3resource</div>
you mean something like this
<html>
<head>
<title>JavaScript basic animation</title>
</head>
<body onload="shubham()">
<div id="target">w3resource</div>
<button onclick="shubham()">click</button>
</body>
</html>
<script>
function shubham() {
var x = document.getElementById('target').textContent;
var y = x.split('');
var z = y[0];
var m = y[y.length - 1];
setInterval(function () {
document.getElementById('target').innerHTML = m + x.substring(0, 8);
}, 500);
}
</script>

How to I auto-update a clock in Javascript? [duplicate]

This question already has answers here:
Run JavaScript function at regular time interval
(4 answers)
setInterval using a non anonymous function requiring parameters has to be inside an anonymous function. Why?
(4 answers)
Closed 6 years ago.
I am trying to make a simple web based clock app using pure java-script. I think the general code is right, but I'm not sure how to automatically call the function at a set interval of time. I thought the window.onload, followed by the setInterval method would do this. But it's not automatically updating every half second as I expected. What am I doing wrong?
<!doctype html>
<html>
<head>
<title>Real Time Clock</title>
<script>
var time, h, m, s, track;
track = 0;
window.onload = function() { setInterval( timeNow(), 100); }
function timeNow() {
time = new Date();
track += 1;
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
if ( s < 10 ) { s = "0" + s; } /* we add a 0 in front of s, when it is lower than 10, because that's what most clocks display, this is for the human user rather than for any need by the computer */
document.getElementById("time").innerHTML = h + ':' + m + ':' + s;
document.getElementById("track").innerHTML = track;
}
</script>
</head>
<body>
<span id="time">~Waiting for time update.</span><br>
<span id="track"></span>
</body>
</html>
Seems to work fine. Just needed to change
window.onload = function() { setInterval( timeNow(), 100); }
to
window.onload = function() { setInterval( timeNow, 100); }
<!doctype html>
<html>
<head>
<title>Real Time Clock</title>
<script>
var time, h, m, s, track;
track = 0;
window.onload = function() { setInterval( timeNow, 100); }
function timeNow() {
time = new Date();
track += 1;
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
if ( s < 10 ) { s = "0" + s; } /* we add a 0 in front of s, when it is lower than 10, because that's what most clocks display, this is for the human user rather than for any need by the computer */
document.getElementById("time").innerHTML = h + ':' + m + ':' + s;
document.getElementById("track").innerHTML = track;
}
</script>
</head>
<body>
<span id="time">~Waiting for time update.</span><br>
<span id="track"></span>
</body>
</html>
use setInterval(timeNow,100); instead of setInterval(timeNow(),100);
var time, h, m, s, track;
track = 0;
window.onload = function() {
var start = setInterval(timeNow,100);
}
function timeNow() {
var time = new Date();
track += 1;
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
if ( s < 10 ) { s = "0" + s; }
document.getElementById("time").innerHTML = h + ':' + m + ':' + s;
document.getElementById("track").innerHTML = track;
}
<span id="time">~Waiting for time update.</span><br>
<span id="track"></span>
You are passing an undefined (as the result of calling timeNow) to setInterval. You need to pass the function, so the code will be:
window.onload = function() { setInterval(timeNow, 100); }

Little mistake somewhere. Help needed

I wrote a little browser-game.
The rules are easy: you have 15 seconds to decide if you know the name written on the screen.
You have two buttons: "i know"/"give up" - depends on what you want to choose.
If you choose "give up" (or time ends) photo 1 appears. Otherwise, photo 2 will be shown.
Whole operation is looped.
Here's my question: I wanted to choose random name from array "word" every single round, so I wrote function "random_word()". I put it into "timer()", "surrender()" and "winning()" functions. But it doesn't work.
I'm just starting with programming, so I'll be grateful for possibly easiest to understand code. Thanks for all help.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<button id= "btnSurrender">give up</button>
<button id= "btnWinning">i know</button>
<p id="seconds">15</p>
<div id="photo"></div>
<script type="text/javascript">
var word = new Array(3);
word[0] = "Michael";
word[1] = "Simon";
word[2] = "Peter";
word[3] = "Mark";
function random_word(){
var randomWord = word[Math.floor(Math.random()*word.length)]
}
var btn1 = document.getElementById("btnSurrender");
var btn2 = document.getElementById("btnWinning");
var pic = document.getElementById("photo");
var secondsP = document.getElementById('seconds');
var clock = null;
btn1.addEventListener("click", surrender);
btn2.addEventListener("click", winning);
function timer () {
random_word();
clearInterval(clock);
var start = new Date().getTime();
clock = setInterval(function() {
pic.innerHTML='<img src="" alt="">';
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
}
if (seconds === 0) {
pic.innerHTML='<img src="mops bops.png" alt="">';
}
}, 1000);
}
function surrender(){
clearInterval(clock);
pic.innerHTML='<img src="mops bops.png" alt="">';
secondsP.textContent = 0;
setTimeout(timer,2000);
word[Math.floor(Math.random()*word.length)]
random_word();
}
function winning(){
clearInterval(clock);
pic.innerHTML='<img src="mopsik.jpg" alt="">';
secondsP.textContent = 0;
setTimeout(timer,2000);
word[Math.floor(Math.random()*word.length)]
random_word();
}
timer();
document.write(randomWord)
setInterval(timer, 17000)
</script>
</body>
</html>
var randomWord;
You need to arrow it at the beginning of the script, before giving a document.write
When I tested your code and set it to the "randomWord" variable at the beginning of the code, it worked; You should do the same, set the variable at the beginning of the code!

How to show text only at specified times

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.

Clock in Javascript

I have made a clock in javascript but its a static clock. What changes I need to do in the following code so that it updates with every second.
<html>
<head>
<title>Javascript Clock</title>
<script type="text/javascript">
function clk() {
var a=new Date();
document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
}
</script>
</head>
<body>
<input type="button" onclick="clk()" value="Display Clock" />
<p id="disp">Clock Space</p>
</body>
</html>
You can use setInterval to run your clk() function every second:
setInterval(clk, 1000); // run clk every 1000ms
MDN on setInterval
As nnnnnn points out, the timer interval probably won't be synchronized with the passage of an actual, real-time second, so using an interval like 100ms might not be a bad idea.
You can add setTimeout(clk,1000); to your function,as bellow:
function clk() {
var a=new Date();
document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
setTimeout(clk,1000);
}
A JavaScript digital clock from system time, can also manually set. :-)
function timer(h,m,s){
var sec;
var min;
var hrs;
var day;
if(((s<=59) && (s>=0)) && ((m<=59) && (m>=0)) && ((h<=23) && (h>=0))){
sec=s;
min=m;
hrs=h;
//set parent element id 'lga' to your id
var parent = document.getElementById('lga');
parent.innerHTML = '';
var child = document.createElement('div');
child.id = "thanesh";
child.style = 'font-size:20px';
parent.appendChild(child);
setInterval(function(){
sec++;
if(sec==60){sec=0;min++;}
if(min==60){min=0;hrs++;}
if(hrs==24){hrs = 0; min = 0; sec = 0;}
if(hrs<=12){
day = 'AM';
}else{
day = 'PM';
}
document.getElementById('thanesh').innerHTML = '<table style="background-color:#f5f5f5;"><tr><td><div id="hh">0</div><td>'
+hrs+' : <td><div id="mm">0</div><td>'
+min+' : <td><div id="ss">0</div><td>'
+sec+' <td>'
+day+'</td></td></td></td></td></td></td></tr></table>';
if(sec>9){
document.getElementById('ss').style.display = "none";
}else if(sec==0){
document.getElementById('ss').style.display = "block";
}
if(min>9){
document.getElementById('mm').style.display = "none";
}else if(min==0){
document.getElementById('mm').style.display = "block";
}
if(hrs>9){
document.getElementById('hh').style.display = "none";
}else if(hrs==0){
document.getElementById('hh').style.display = "block";
}
},
1000);
}else{
alert("Check time inputs...!");
}
}
//Set Hour, Minutes, Seconds by JS / manually
var date = new Date();
var hst = date.getHours();
var mst = date.getMinutes();
var sst = date.getSeconds();
timer(hst,mst,sst);
Since your "update every second" of the real clock competes with other computer tasks, the delay before the next real clock tic will be less than 1000 ms very often. So, better use setTimeout instead of setInterval. In fact, we just need to twist a little bit the end of the denied 姚先进's solution here arround, resulting in:
function clk() {
var a=new Date();
document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
setTimeout(clk, 1000 - a % 1000);
}
This is my clock solution since 2007.
here we go
<html>
<head>
<title>Javascript Clock</title>
<script type="text/javascript">
function clk() {
setInterval(() => {
var a = new Date();
document.getElementById("disp").innerHTML = a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds();
},1000);
}
</script>
</head>
<body>
<input type="button" onclick="clk()" value="Display Clock" />
<p id="disp">Clock Space</p>
</body>
</html>

Categories