Why isn't my web page displaying the time (javaScript) - javascript

Hey guys in my head I have linked the java script file
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tech News</title>
<link href="layout.css" rel="stylesheet" type="text/css" />
<script type ="text/javascript" src=" script.ja"> </script>
and in the java script file I have this code
window.onload = initDate;
function initDate()
{
now = new Date();
localtime = now.toString();
globaltime = now.toGMTString();
document.write("<b> Local time: </b> " + localtime + "<br>");
hours = now.getHours();
mins = now.getMinutes();
secs = now.getSeconds();
document.write ("<font size = '+1'>");
document.write(hours + ":" + mins +":" + secs);
document.write("</font>");
document.getElementById("time").innerHTML = dtString;
}
Now this code should display the string in thie div tag but it doesn't
document.getElementById("time").innerHTML = dtString;
Here is the div tag.
<div id="time"> <!--Time-->
</div>
My website is 100& verified with no coding errors, both HTML and CSS.
So what will be the problem?

Thanks to Patrick I realized that I did not declare dtString.
Instead of complicating things the simple solution was to copy the text in to a div tag, which I had found useful since it displayed the date and time.
<div id="date">
<script>
now = new Date();
localtime = now.toString();
globaltime = now.toGMTString();
document.write(localtime);
hours = now.getHours();
mins = now.getMinutes();
secs = now.getSeconds();
document.write ("<font size = '+1'>");
document.write(hours + ":" + mins +":" + secs);
document.write("</font>");
</script>
</div>

Related

How should I use setTimeout in this Javascript real-time-clock?

I was trying to do a real-time-clock but I'm having a problem, the setTimeout isn't working in fact the clock doesn't update itself. May I have your help please?
This is the code that I wrote:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
var currentDate = new Date();
function startClock() {
time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
document.getElementById("p").innerHTML = time;
setTimeout(startClock, 1000);
}
startClock();
</script>
</body>
</html>
Actually, the setTimeout is working fine, however you instantiate currentDate outside of the function, so it never updates.
This is because the time is only captured when the date is instantiated-- it doesn't update itself. That means if you only instantiate it once, it will only ever hold the time from when it was instantiated.
Try this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
function startClock() {
var currentDate = new Date();
time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
document.getElementById("p").innerHTML = time;
setTimeout(startClock, 1000);
}
startClock();
</script>
</body>
</html>
Use setTimeout is correct.
But it is not best solution.
Because it will consume memory exponentially when you call itself.
So, you can use setInterval instead of setTimeout:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
function startClock() {
let currentDate = new Date();
time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
document.getElementById("p").innerHTML = time;
}
setInterval(startClock, 1000);
</script>
</body>
</html>

Using JavaScript To Change the HTML Contained In An External Script

I have an element on my website that is hosted externally and referenced in a script on my page.
I want to automatically change the text within this content so that it always displays tomorrow's date.
Script for the widget:
<script src="//my.externalwidget.com/12345.js" type="text/javascript" charset="utf-8" async="async"></script>
HTML contained in external script:
<div id="changeHeaderOne">THIS SHOULD DISPLAY TOMORROW'S DATE</div>
My JS:
<script type="text/javascript">
var currentDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var dateParse = currentDate.toString();
var dayAbbr = dateParse.substr(0, 3);
var day = currentDate.getDate();
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
document.getElementById("changeHeaderTwo").innerHTML = "Tomorrow's date is " + dayAbbr + " " + month + "/" + day + "/" + year;
document.getElementById("changeHeaderOne").innerHTML = "Tomorrow's date is " + dayAbbr + " " + month + "/" + day + "/" + year;
I know my script is working because it runs properly on #changeHeaderTwo (located in DOM) but not on #changeHeaderOne (externally hosted and loaded using the script on top).
Any ideas how to make this apply to the externally loaded code as well?
You are using document.getElementByClass() (which should really by document.getElementsByClassName()) when your div has an id. Use document.getElementById() instead.

onload doesn't work while onmouseenter does

I have done a simple JS function and tried to call it with onload="updateClock()" but without any success. But if i change to onmouseenter="updateClock()" it works perfectly then I hover over with the mouse.
Why doesn't it work?
HTML:
<script src="clock.js" type="text/javascript"></script>
<section onload="updateClock();">
<span id="clock">00:00:00</span>
</section>
JS:
function updateClock(){
var currentTime = new Date ();
var hours = currentTime.getHours ();
var minuts = currentTime.getMinutes ();
var seconds = currentTime.getSeconds ();
//Pad with zeros
hours = (hours < 10 ? "0" : "") + hours;
minuts = (minuts < 10 ? "0" : "") + minuts;
seconds = (seconds <10 ? "0" : "") + seconds;
var time = hours + ":" + minuts + ":" + seconds;
document.getElementById("clock").innerHTML = time;
}
Only elements like iframe or img, in general, elements which can have content loaded from an external resource, have onload event. (And some DOM objects, like window ofcourse.)
A quick-fix would be to move the script tag after the section and use an IIFE:
<section>
<span id="clock">00:00:00</span>
</section>
<script src="clock.js" type="text/javascript"></script>
And in clock.js:
(function updateClock(){
:
}());

when implementing javascript countdown the other html elements disappear

I made a layout and had everything set and when I implement the counter portion under my text all the other HTML elements disappear why is that? Also is there any way I can make an email alert when the counter gets to a specific time?
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-
scalable=0, width=device-width;">
<title>Welcome to Tiffany & Co.</title>
<link rel="stylesheet" href="index.css"
type="text/css" media="screen" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<!--Enable media queries in some unsupported subrowsers-->
<script type="text/javascript" src="css3-mediaqueries.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div id="wrapper">
<h1>Welcome to Store</h1>
<p>The WiFi Password is:</p>
<h2 align=center>
<font color="red">Diamonds</font>
</h2>
<p>It will change in:</p>
<p>
<script type="text/JavaScript">
window.document.onload = function () {
tick();
setInterval(tick, 1000);
};
function tick() {
var d = new Date();
var currentDate = new Date(d.getUTCFullYear(),
d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(),
d.getUTCMinutes(), d.getUTCSeconds(),
d.getUTCMilliseconds());
var endDate = new Date(currentDate.getFullYear(),
currentDate.getMonth(), currentDate.getDate() + (30
/*
saturday */
- currentDate.getDay()), 16
/* 9 AM Mountain
Time = 4 PM GMT */
);
var secondsUntilSaturday = Math.floor((endDate.getTime() - currentDate.getTime()) / 1000);
var timeUntilSaturday = secondsToTime(secondsUntilSaturday);
document.body.innerHTML = (timeUntilSaturday.h + " hours, " + timeUntilSaturday.m + " minutes, " + timeUntilSaturday.s + "
seconds");
}
function secondsToTime(secs) {
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
var obj = {
"h": hours,
"m": minutes,
"s": seconds
};
return obj;
}
</script>
<div id="logo">
<img src="logo.png" width="108" height="14" alt="Tiffany & Co." />
</div>
</div>
</body>
</html>
Your HTML content disappears because of the line:
document.body.innerHTML = (timeUntilSaturday.h + " hours, " + timeUntilSaturday.m + " minutes, " + timeUntilSaturday.s + " seconds");
document.body.innerHTML will write content to the body element, replacing anything that's there. You can replace document.body.innerHTML with document.write.
To answer your second question, no JavaScript can't send email on it's own, but via AJAX it can call a script on your server to send email.
That's because you're replacing whole body content with your timer
document.body.innerHTML = (
timeUntilSaturday.h +" hours, "+
timeUntilSaturday.m +" minutes, "+ timeUntilSaturday.s +"
seconds"
);
Instead of this add <div> for timer and set content with your timer
<div id="timer"></div>
<script>
document.getElementById('timer').innerHTML = (
timeUntilSaturday.h +" hours, "+
timeUntilSaturday.m +" minutes, "+ timeUntilSaturday.s +"
seconds"
);
</script>
Since you're refrencing JQuery, I've used that for you, but really only in one spot...
This should do what you need it to do: Here's a fiddle
Also here's the code from that fiddle:
<script>
//start your interval to update your timer.
setInterval(function() {
//get ms until Saturday 9AM.
var ms = untilTimeOfWeek(6, 9, 0, 0);
$('#timer').text(getHours(ms) + ' hours ' + getMinutes(ms) + ' minutes ' + getSeconds(ms) + ' seconds');
}, 100);
//gets the time left until a specific time of week.
function untilTimeOfWeek(day, hour, min, sec) {
var currdate = new Date();
var currday = currdate.getDay();
var daydiff = (day - currdate.getDay()) * 86400000;
var hourdiff = (hour - currdate.getHours()) * 3600000;
var mindiff = (min - currdate.getMinutes()) * 60000;
var secdiff = (sec - currdate.getSeconds()) * 1000;
return daydiff + hourdiff + mindiff + secdiff;
}
//get the hours from some milliseconds.
function getHours(ms) {
return Math.floor(ms / 3600000);
}
//get the minutes from some milliseconds.
function getMinutes(ms) {
return Math.floor((ms % 3600000) / 60000);
}
//get the seconds from some milliseconds.
function getSeconds(ms) {
return Math.floor(((ms % 3600000) % 60000) / 1000);
};​
</script>
<div id="timer"></div>
NOTE: +new Date is just shorthand for converting a Date to a numeric type in JavaScript.
I hope that helps.
EDIT: Updated to get 9am the following Saturday.

How to display system time?

I want to display the system time on my jsp page. How can i do it? I'm trying this but only date is getting displayed that and not the time. It's all working fine in Internet Explorer but not in other browsers.
<td colspan="1" height="4" align="left" width="260" >
<font class="welcome1">
<strong>
<script language="JavaScript" src="js/date.js"></script>
<span id="clock">
<script language="JavaScript"
src="js/digitalClock.js"></script>
</span>
</strong>
</font>
</td>
Displaying the time on a web-page using js should be trivial .
new Date().toLocaleString() // displays date and time
new Date().toLocaleDateString() // displays date
new Date().toLocaleTimeString() // displays time
To display time you can use Date.
<html>
<head>
<script type="text/javascript">
<!--
function updateTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
if (minutes < 10){
minutes = "0" + minutes;
}
if (seconds < 10){
seconds = "0" + seconds;
}
var v = hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
v+="PM";
} else {
v+="AM"
}
setTimeout("updateTime()",1000);
document.getElementById('time').innerHTML=v;
}
updateTime();
//-->
</script>
</head>
<body>
<h4>Current Time: <span id="time" /></h4>
</body>
</html>
I've tested it in firefox and chrome. Found on this site.
Edit: time now gets updated every second.
You should read the documentation about the Date object in JavaScript (Date). It would be easier if you post the JS source.
/* set Date */
function tick() {
/* Get date in epoch */
var epoch = Date.now();
document.querySelector("#epoch").innerHTML = epoch;
/* Separate epoch */
var datetime = new Date(epoch);
var year = datetime.getFullYear();
var month = datetime.getMonth() + 1; // (0-11)
var date = datetime.getDate();
var hour = datetime.getHours();
var minute = datetime.getMinutes();
var second = datetime.getSeconds();
document.querySelector("#datetime").innerHTML =
year + "-" + addZero(month) + "-" + addZero(date) + " " +
addZero(hour) + ":" + addZero(minute) + ":" + addZero(second);
}
// Add 0 if argument < 10
function addZero(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
/* Call tick in interval 1 second */
setInterval(tick, 1000);
<p id="epoch"></p>
<p id="datetime"></p>
This seems the easiest solution, which uses setInterval with two arguments, the first being a callback, the second the interval in ms:
setInterval(function(){
document.write(new Date().toLocaleTimeString();
},1000);
So my solution should be the accepted answer because it is a real time.
For Date You can use below Javascript. Time will display in a text box. You can modify as per your requirement.
<html>
<head>
<script type="text/javascript">
var timer = null
function stop()
{
clearTimeout(timer)
}
function start()
{
var time = new Date()
var hours = time.getHours()
var minutes = time.getMinutes()
var seconds = time.getSeconds()
var clock = hours + ":" + minutes + ":" + seconds
document.forms[0].display.value = clock
timer = setTimeout("start()",1000)
}
</script>
</head>
<body onload="start()" onunload="stop()">
<form>
<input type="text" name="display" size="20">
</form>
</body>
</html>

Categories

Resources