Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

question about external *.js file

Status
Not open for further replies.

geramis

Programmer
Oct 10, 2001
14
IL
i have a javascript file called general.js, which contains
general info, for example:

var link="var user="myUser";

QUESTION:
when i link an external .js file into my HTML, for example:
<html>
<head>
<script language=&quot;javascript&quot;>test.js&quot;></script>
</head>
....
</html>

can i use variables and functions inside the test.js file, that are written in the general.js file, for example:

alert(link); // link is defined in the general.js file
 
Yes, you sure can. However you are going to need to comply by these rules regarding external .js files.

#1: I'm concerned about your line that references the .js file. It needs to look like this..
Code:
<html>
 <head>
   <script language=&quot;javascript&quot; src=&quot;test.js&quot;></script>
 </head>
....
</html>

#2: Make sure you do not put <script> </script> tags in your .js files.

#3: The variable you define in the .js file must be outside of any functions. It must be a global variable. (And it looks like you're doing that)

#4: The variable you define in the .js file must be defined before the code that wants to access it is fired.

I ran a simple test with three files.

test1.html
Code:
<html>
<head>
<script Language=&quot;JavaScript&quot; src=&quot;test.js&quot;></script>
<script Language=&quot;JavaScript&quot; src=&quot;general.js&quot;></script>
</head>
<body onLoad=&quot;popAlert();&quot;>
</body>
</html>

test.js - Just this one line
Code:
var link = &quot;[URL unfurl="true"]www.mywebsite.com&quot;[/URL]

general.js - Just this one line
Code:
function popAlert() {
  window.alert(link)
}

When the html page loads, it calls the function in general.js which accesses the variable in test.js It works just great.

Hope this helps..

ToddWW
 
dang todd! very descriptive. good job. but it can be said in a simple sentence, I believe.

Write your javascript on the page, then just copy out the text from the html page and paste it into the .js file.

(of course, you should refrence it at the top of the page, just below the <title></title> tags.) theEclipse
eclipse_web@hotmail.com
Icq: 124408594
online.dll

AIM & MSN: robacarp
 
Yes, you're right. I've been known to over simplify things from time to time. And in some cases, it becomes more confusing than it really should be. And this is probably one of those cases.

Nonetheless, that's the beauty of forums right !! :)

ToddWW
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top