Javascript Location - Does a Javascript function have to be in the same page? (Posted by Ray)

They have: 15 posts

Joined: Sep 1999

My web page code is getting cluttered and I am trying to be more efficient. I have several Javascripts that are running on all my web pages - is it possible to put them (the Javascript functions) in an HTML page all their own and call them when I need them?

If this can be done, how do I call the function? Here's my example of calling the function when it's located in the same page as the callout.

<a href="javascript:navigate()">
<img src="graphics/button.gif" vspace="" hspace=""></a>

Of course, the function is located in the <HEAD> </HEAD> of this document. If I can move the function into another document for efficiency's sake, say into a "script" directory and place it into a "jscripts.htm" document, what would the callout string look like?

So far, I've tried

<a href="scripts/jscripts.htm:javascript:navigate()">
<img src="graphics/button.gif" vspace="" hspace=""></a>

and

<a href="scripts/jscripts.htm:'javascript:navigate()'">
<img src="graphics/button.gif" vspace="" hspace=""></a>

and

<a href="scripts/jscripts.htm'javascript:navigate()'">
<img src="graphics/button.gif" vspace="" hspace=""></a>

I haven't found any documentation that said I could not do it but have not found any examples that say I could either.

Can it be done and I am doing it wrong? The above tries were just guesses -

Any help would be much appreciated!!

Many Thanks in advance!

Ray

They have: 5,633 posts

Joined: Jan 1970

Yes you can do what your after. This involves JS files. These are simply plain text files with only JavaScript code inside. These are inserted into the <HEAD></HEAD> tags then you can call the function from your document.

<script language="javascript" src="FILE.js"></script>

Here is an example of a JS file.


<!-- hide script from old browsers

// preload images
if (document.images) {
next = new Image();
next.src = "images/next.gif";
}

function alertBox(message) {
alert(message);
}

// end hiding from old browsers -->

I'm not too sure what browsers support JS files but If you ask someone here I'm sure they will know the answer.

----------
[email protected]
http://go.to/hass

They have: 15 posts

Joined: Sep 1999

Thanks again Lloyd for the answer and I'll do another post and see if anyone can help out on which browsers support js files!!

Appreciate it!!

Ray

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.