ANKIT CHAUDHARY
ANKIT CHAUDHARY

Reputation: 11

call an external js file's function in html

I have tried to print time in html file using an external js file, but not able to print the time. If i use external js as inline than it print the time. Why so?

My source code:

time(){
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];
document.writeln("Today is : " + daylist[day] + ".");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var prepand = (hour >= 12) ? " PM " : " AM ";
hour = (hour >= 12) ? hour - 12 : hour;
if (hour === 0 && prepand === ' PM ')
{
    if (minute === 0 && second === 0)
    {
        hour = 12;
        prepand = ' Noon';
    }
    else
    {
        hour = 12;
        prepand = ' PM';
    }
}
if (hour === 0 && prepand === ' AM ')
{
    if (minute === 0 && second === 0)
    {
        hour = 12;
        prepand = ' Midnight';
    }
    else
    {
        hour = 12;
        prepand = ' AM';
    }
}

document.write("Current Time : " + hour + prepand + " : " + minute + " : " + second);
}
  
<html>
  <head>
  <meta charset="utf-8">
 
  <link rel="stylesheet" type="text/css" href="watchdiv.css">
 
  <title>JavaScript current day and time</title>  
  </head>
  <body>
  <div id="watch">
 <script src="watch.js">time()</script>
  
  </div>
  </body>
</html>

What i missing to get result? in div tag no result print

Upvotes: 1

Views: 1158

Answers (4)

Darshan Patel
Darshan Patel

Reputation: 2899

You are doing loading and executing both at same time.

Since Javascript is synchronous. So, first you have to load file and next script tag would be execution code.

<script type="text/javascript" src="watch.js"></script>

<script>
   time();
</script>

Upvotes: 0

Chathura Edirisinghe
Chathura Edirisinghe

Reputation: 367

datestmp.js:

date()
function date(){
test = new Date()
month = test.getMonth()
month = (month * 1) + 1
day = test.getDate()
year = test.getFullYear()
document.write(" ",month,"/",day,"/",year," ")
}

In Your HTML:

<script src="datestmp.js">
</script>

Upvotes: 0

Eyzi
Eyzi

Reputation: 516

Try:

<script src="watch.js"></script>
<script>time();</script>

Upvotes: 1

MartinWebb
MartinWebb

Reputation: 2008

This is more than likely becuase the file does not load in-time and thus the script block that calls the time function fails.

Move the script tag that loads the file to the bottom of your html file. Ideally you should use some code logic that detects when the file is loaded. If you use a library like jquery this has just that pre-installed.

You are also doing this wrong, you need two tags one loads the script one runs your function.

<script src="watch.js"></script>
<script>time();</script>

Upvotes: 1

Related Questions