...

View Full Version : Moving a script from the body of a html page and place it in a .js script - Cured



smiffy
10-24-2005, 12:28 AM
Javascript is not my strongest of languages to say the least, but I want to be able to move a script out of the body section of a html page and place it in a .js script so that I can call it as a function from <img src="javascript:myfunction()" /> but I am missing that extra bit of code to make it work...

This is the script that is working in the body tag:

<script>
var day = new Date()
var hr = day.getHours()

if (hr < "9") {
document.write('<img src="images/closed_sign.gif" />')
}
else if (hr > "8")
if (hr < "18") {
document.write('<img src="images/open_sign.gif" />')
}
else if (hr > "17") {
document.write('<img src="images/closed_sign.gif" />')
}
</script>
The script basically shows a different image depending on the time of day.

I've tried:

function myfunction(){

var day = new Date()
var hr = day.getHours()

if (hr < "9") {
document.write('images/closed_sign.gif')
}
else if (hr > "8")
if (hr < "18") {
document.write('images/open_sign.gif')
}
else if (hr > "17") {
document.write('images/closed_sign.gif')
}
}
This just displays a blank page containing - images/closed_sign.gif

Anybody have any ideas?

_Aerospace_Eng_
10-24-2005, 01:22 AM
Use the document.writes to right out the whole image tags.
Put this in an external JS, call it timeofday.js

var day = new Date()
var hr = day.getHours()

if (hr < "9") {
document.write('<img src="images/closed_sign.gif" alt="" />')
}
else if (hr > "8")
if (hr < "18") {
document.write('<img src="images/open_sign.gif" alt="" />')
}
else if (hr > "17") {
document.write('<img src="images/closed_sign.gif" alt="" />')
}
Then where you want it to appear put this in your body tag.

<script type="text/javascript" src="timeofday.js"></script>
Are you sure the script works? I think getHours() returns a number not a string.

smiffy
10-24-2005, 01:49 AM
Are you sure the script works? I think getHours() returns a number not a string.You are right that it returns a number... it is that number that the script queries to produce the relevant image.

I tried your code and I am now getting a full page content but unfortunately the image shows in the very top left corner of the browser window. I tried holding the script inside a div but got the same results. This seems weird to me!


EDIT: I'm a donut... I left the script reference in the <head> section and didnt assign the full path to the newly created .js script in the <body> element. Thanks _Aerospace_Eng_ you code works.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum