Reputation: 81
I just started to learn web development and I am having some trouble. I want to have a clock show up on my home page. Just a running clock. I used an example from w3 but they have it all in the html and I wanted to use a separate file. When I launch the site nothing happens and the clock doesn't show up. When I put the showtime in a script tag by itself into the jsp it works.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script lang="javascript" type="text/javascript" src="JavaScript/showtime.js"></script>
</head>
<body>
<p>Test</p>
<div id="txt"></div>
<p>Hello World</p>
<p>test2</p>
</body>
showtime.js
function startTime() {
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
startTime();
Upvotes: 1
Views: 118
Reputation: 4411
@developerwjk's answer is quite possibly correct but it's likely to not be the whole answer. Your javascript is in the head, so it will be run before the DOM is ready (in other words, before the txt element is available), so the call to startTime();
will result in a javascript error, and the clock will never start running.
Change the line startTime();
as follows:
window.onload = function() { startTime(); };
Alternatively, include this javascript file immediately before the closing </body>
tag.
Upvotes: 2
Reputation: 8659
Its a relative path issue. You have to get the relative path of your script to your present html/jsp file's location correct.
Try changing
src="JavaScript/showtime.js"
to (if its in the same dir)
src="./JavaScript/showtime.js"
or (if its one back)
src="../JavaScript/showtime.js"
Upvotes: 0