Move javascript clock code from html file to an external .js file - javascript

So I have made a clock, it works great. Now I want to move the javascript into an external file and link to it with
<SCRIPT type="text/javascript" language="JavaScript" src="clock.js"
</SCRIPT>
I can not figure out how to keep it updating though. I have tried a few things and the results where: time is static at when the page loads, the prints across the screen for every update, and no time at all.
<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>

Here's how I would do it. Put this code in your external js file:
function startTime() {
var today=new Date(),
h=today.getHours(),
m=today.getMinutes(),
s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
}
function checkTime(i) {
if (i<10) {
i="0" + i;
}
return i;
}
And then in your main html page, something like this:
<body onload="setInterval(startTime, 500);">

You're missing ending >
<SCRIPT type="text/javascript" language="JavaScript" src="clock.js">
so it should be
<SCRIPT type="text/javascript" language="JavaScript" src="clock.js">
</SCRIPT>

Related

JavaScript function can't be run in external file

I have two functions in external file, then I call A and B in HEAD script, and A can be run and B can't, but if I put B into head script, B also can be run. I am not sure why, what can I do?
HTML:
<head>
<script language="JavaScript" type="text/JavaScript">
<!--
function B(id) {
var selected = document.getElementById(id)
var arr = selected.options[selected.selectedIndex].text.split(" ");
var value = ""
for (var i = 1; i < arr.length; i++) {
if (value != "") value = value + " ";
value = value + arr[i];
}
return value;
}
function save() {
A("msg");
var x = B(id);
}
-->
...
<script type="text/JavaScript" src="js/my.js"></script>
</body>
...
my.js:
function A(msg) {
scroll(0,0);
var outerPane = document.getElementById('FreezePane');
var innerPane = document.getElementById('InnerFreezePane');
if (outerPane) outerPane.className = 'FreezePaneOn';
if (innerPane) innerPane.innerHTML = msg;
}
function B(id) {
var selected = document.getElementById(id)
var arr = selected.options[selected.selectedIndex].text.split(" ");
var value = ""
for (var i = 1; i < arr.length; i++) {
if (value != "") value = value + " ";
value = value + arr[i];
}
return value;
}
The safest thing to do is wrap the code in the head in a window.onload handler like this...
<head>
<script type="text/javascript">
window.onload = function(){
// your external files are guaranteed to be loaded now
// you can call A or B
}
</script>
</head>
onload is only fired after all external scripts have been loaded.
Here is a full example...
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
<script>
function save() {
A()
B()
}
window.onload = function() {
save()
}
</script>
</head>
<body>
The content of the document......
<script src="./external.js"></script>
</body>
</html>
external.js
function A() {
alert('A ran')
}
function B() {
alert('B ran')
}
NOTE: This is better than moving the external script to the head, like the other answers suggest, because external resources loaded in the head block the entire page render until they are loaded.
By leaving the external script at the end of the body tag, the page load will seem faster as the css/html will display immediately. Even if the javascript isn't loaded yet.
Add your external file before the script tag contains your "save" function.
<script language="JavaScript" src = "yourfile.js" type="text/JavaScript">
</script>
<script language="JavaScript" type="text/JavaScript">
function save(){
A();
B();
}
</script>

Simple javascript for a clock not working

Hi this is my first javascript and it is not working. The script is programmed to display a clock. The code is as follows:
<html>
<head>
<script type="text/javascript" src="clock.js" > </script>
</head>
<body onload=display_ct();>
<span id='ct' ></span>
</body>
</html>
The javascript is :
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var strcount
var x = new Date()
document.getElementById('ct').innerHTML = x;
tt=display_c();
}
When execute I get a blank screen. What and where is the mistake ?
TIA :)
You should probably be consistent with ending lines in semi-colon. Also, you should check that clock.js is loading; finally put the onload handler in quotes like
function display_c() {
var refresh = 1000; // Refresh rate in milli seconds
mytime = setTimeout('display_ct()', refresh);
}
function display_ct() {
var x = new Date();
document.getElementById('ct').innerHTML = x;
tt = display_c();
}
<html>
<body onload="display_ct();">
<span id='ct'></span>
</body>
</html>
Please enclose your onload attribute value of body tag inside " " .
It should be
<body onload="display_ct();">
Try using setInterval(), also this line won't work in some browsers:
setTimeout('display_ct()',refresh)
var ct;
function display_c() {
//timer block
setInterval(function() {
ct.innerHTML = new Date().toString();
}, 1000); //execute every 1 second
}
function display_ct() {
ct = document.getElementById('ct'); //initialize once.
display_c();
}
<!-- onload, enclosed in quotes -->
<body onload="display_ct()">
<span id='ct'>Loading ...</span>
</body>
You made two errors when entering the display_ct function. You needed to wrap the <body>'s onload event with quotes, and remove the quotes and the parentheses on the setTimeout. See below.
function display_c() {
var refresh = 1000; // Refresh rate in milli seconds
mytime = setTimeout(display_ct, refresh);
}
function display_ct() {
var x = new Date();
document.getElementById('ct').innerHTML = x;
display_c();
}
<html>
<head>
<script type="text/javascript" src="clock.js">
</script>
</head>
<body onload="display_ct()">
<span id='ct'></span>
</body>
</html>

JavaScript clock based on TimeAPI

I want to create a JavaScript clock based on TimeAPI.org.
The reason is I want to make sure the client-side has the exact the same time as the server.
In svclock(json) it saves year/month/day/hour/...etc in vars
but when I'm trying to put those vars in setHours in my clock fucnction
the clock's format becomes like this:
1391670641381:1391670761381:1391670727381
instead of 15:27:06.
Is there an easier way to do this?
<html>
<head>
<script>
var svtime,svyear,svmonth,svdate,svday,svhour,svmin,svsec,newtime;
function svclock(json) {
svtime=new Date(json.dateString);
svyear=String(svtime).substr(11,4);
svmonth=String(svtime).substr(4,3);
svdate=String(svtime).substr(8,2);
svday=String(svtime).substr(0,3);
svhour=String(svtime).substr(16,2);
svmin=String(svtime).substr(19,2);
svsec=String(svtime).substr(22,2);
newtime=svhour+':'+svmin+':'+svsec;
//newtime=svyear+'/'+svmonth+'/'+svdate+'('+svday+')'+' '+svhour+':'+svmin+':'+svsec;
}
function startTime()
{
var today=new Date();
var h=today.setHours(svhour);
var m=today.setMinutes(svmin);
var s=today.setSeconds(svsec);
document.getElementById('clock').innerHTML=h+":"+m+":"+s;
t=setTimeout(function(){startTime()},1000);
}
</script>
<script type="text/javascript" src="http://timeapi.org/gmt/now.json?callback=svclock"></script>
</head>
<body onload="startTime()">
<div id="clock"></div>
</body>
</html>

How do I reference jQuery from my HTML/JavaScript application?

I keep getting Uncaught ReferenceError: $ is not defined error.
I assume everything is ok and working. My JQuery code is inside my Javascript file. I assume that isn't how it works? Should I have a JQuery file?
I have this inside the head of my HTML
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
This is my Javascript file:
function typing(id, sentence){
var result = $.Deferred();
var index=0;
var intObject= setInterval(function() {
document.getElementById(id).innerHTML+=sentence[index];
index++;
if(index==sentence.length){
clearInterval(intObject);
}
}, 100);
return result.promise();
}
var sleep = function(ms) {
var result = $.Deferred();
setTimeout(result.resolve, ms);
return result.promise();
};
typing('container','Subject Name:').then(function() {
return sleep(500);
}).then(function() {
return typing('container',' Carlos Miguel Fernando')
});
Where did I go wrong?
Your question is fairly unclear, but essentially, you just have to make sure jQuery is loaded before your code. So for instance:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="your-code.js"></script>
or
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
// Your code
</script>
But not
<!-- Not like this -->
<script src="your-code.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
Note the order of tags.
These tags do not need to be in the head, and in fact, putting them there is not best practice. They must be in head or body. Best practice barring a specific reason to do something else is to put them at the very end of body, e.g.:
<!-- site content here -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="your-code.js"></script>
</body>
</html>

Issue with wisdom generator

I am trying to display random wisdom on a web page but I cannot figure out why the code below does not work.
Thank you
My javascript external file is:
function random(low, high) {
return Math.floor(Math.random()*(high-low+1)) + low;}
function randomarr() {
var arr = new Array("...1", "...2", "...3");
return arr[random(0, arr.length-1)];}
function display(){
var k = randomarr();
alert(k);}
and my html file
In the head section I've got:
<script type="text/javascript">
src="java.js"
</script>
And in the body section I've got:
<p>
<script type="text/javascript">
document.write(display());
</script>
</p>
The syntax for including the script in the <head> is wrong. Try this:
<script type="text/javascript" src="java.js"></script>

Categories