The SitePoint Forums have moved.

You can now find them here.
This forum is now closed to new posts, but you can browse existing content.
You can find out more information about the move and how to open a new account (if necessary) here.
If you get stuck you can get support by emailing forums@sitepoint.com

If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

javascript in HEAD tag doesn't work

i'm having problems with this piece of code in that if i put it in the HEAD tag it doesn't work..if i put the SCRIPT below the P tags it works fine; I don't see any logical reason for it to not work when placed in the HEAD tag?

Is there any workaround to make it work in the HEAD tag? It would be even better if I could link it outside of the html document

errr sorry but i know how to link to an external file, but the problem is that this javascript code is not working when placed in the HEAD tag; see the code is below the P tags, they are there now because it's the only place at the moment that's working and my question was why it doesn't work if I move this piece of javascript to within the HEAD tag

Most javascripts will work in the <head> of the document. The killer for your script is this line ...

fontObj=document.getElementById("body").childNodes[0]

... If the code is in the <head> then the <body> tag has not yet been written and so fontObj will be "undefined". Putting it at the bottom of your page works because pretty much all the page elements exist by then.

I should also say the type="text/javascript" is the correct definition.

It'll all depend on when certain parts of the code are executed. In your code above, the "textObj=..." and "fontobj=..." lines are outside of functions, so they will be executed as the browser loads the page. If they're in the header, then the elements they are attempting to access might/will* not exist yet.

*this is fuzzy, and may even vary from machine to machine and browser to browser.

However, I'll predict that if these lines were INSIDE the functions, then they wouldn't get executed until the functions were triggered by user actions. At that point, the objects WOULD exist, so the code should work.

In this way, some code in the header will work, but slightly different code will fail.