Report this

What is the reason for this report?

How can I link my Javascript function in an external file to my html file?

Posted on July 19, 2021

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();


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

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.

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.

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.