How can I link my Javascript function in an external file to my html file? Here you can see my code from my html and Javascript. I tried with the <script> but this didn’t work out :(
**HTML**
<html>
<head>
<title>Digital Clock</title>
<link rel="stylesheet" href="clock.css">
</head>
<body>
<h1>Digital Clock</h1>
<script type="text/javascript" src="clock.js"></script>
</script>
</body>
</html>
**Javascript**
function showTime(){
var date = new Date();
var h = date.getHours(); // 0 - 23
var m = date.getMinutes(); // 0 - 59
var s = date.getSeconds(); // 0 - 59
var session = "AM";
if(h == 0){
h = 12;
}
if(h > 12){
h = h - 12;
session = "PM";
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ":" + m + ":" + s + " " + session;
document.getElementById("MyClockDisplay").innerText = time;
document.getElementById("MyClockDisplay").textContent = time;
setTimeout(showTime, 1000);
}
showTime();
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Click below to sign up and get $100 of credit to try our products over 60 days!
Hi @sjoerd2002
I can see in your function that you are trying to get an HTML element by id which should be MyClockDisplay however I can’t see that element ID anywhere in your HTML code.
Basically, you want to create a div where the ID would be MyClockDisplay and it would display the time.