2

I have JS code in both the body and head portions of my page. If I wanted to have them be in an external .js file, how would I move them over and then call them back onto the page?

Head -

<script language="Javascript">
setInterval("settime()", 1000);

function settime () {
var curtime = new Date();
var curhour = curtime.getHours();
var curmin = curtime.getMinutes();
var cursec = curtime.getSeconds();
var time = "";

if(curhour == 0) curhour = 12;
time = (curhour > 12 ? curhour - 12 : curhour) + ":" +
     (curmin < 10 ? "0" : "") + curmin + ":" +
     (cursec < 10 ? "0" : "") + cursec + " " +
     (curhour > 12 ? "pm" : "am");

document.date.clock.value = time;
}
</script> 

Body -

<script language="JS" type="text/javascript">
var monthArray = new Array("January", "February", "March", "April", "May",
                       "June", "July", "August", "September",
                       "October", "November", "December");

var today = new Date();
var todayMonth = today.getMonth();
var todayDate = today.getDate();
var todayYear = today.getFullYear();
document.write(monthArray[todayMonth] + " " + todayDate + ", " + todayYear);
</script>

1 Answer 1

2

Move your JS code into an external file (say, my.js) and include it within your page as :

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

Of course, the above assumes that my.js lies in the same folder/directory as your page. you'll need to adjust the src value as per the location of you JS file.

Sign up to request clarification or add additional context in comments.

5 Comments

As far as the external .js file goes, do I include everything that is between the <script></script> tags, excluding them?
Yes, that is correct. Ensure that you put all of the script code from both the head and body portions, since it is possible that you have some overlapping JS code across the two.
Not really. If you don't have tons of lines of JS code, you should be able to figure it out with a look.
Ok. Thank you. You've been a great help. Double plus for helping so much :)
No problems! Looking at your code above, doesn't look like you have duplicate code across the two scripts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.