views:

70

answers:

5

Hi,

I want to pass a parameter to some javascript using a single line of code, like this:

<script language="JavaScript" src="courselist.js?subj=MATH" type="text/javascript" />

Inside the javascript file, how can I get the value of the parameter "subj"?

Thanks

+5  A: 

That's as far only possible by accessing "own" <script> element in the HTML DOM and parse the src attribute.

Long story short, here's a nice article with detailed explanations and code samples: http://feather.elektrum.org/book/src.html

BalusC
heh wow. I guess everything's possible
Earlz
+1 it **is** possible.
alex
This is excellent, it worked. Thanks
jeph perro
You're welcome.
BalusC
A: 

I don't think the Javascript file would be aware of the parameter that is passed to it. If that address goes to some sort of server-side script (NOT just a static Javascript file), then you may be able to do something with it.

mikez302
+2  A: 

The only way to get something like this to work is to have the server serving up a dynamically generated javascript file where it has something like this on the server:

if(Parameters["subj"]=="MATH"){
  jsfile="var subj='MATH'; "+jsfile;
}...
Earlz
+5  A: 

Why not just create the variable in inside a script tag before including the javascript file?

<script type="text/javascript">
    var subj = "MATH";
</script>
<script language="JavaScript" src="courselist.js" type="text/javascript"></script>
okalex
This is how I have done it now, I was trying to keep the code to a single line. This line of code is going to be used to include some dynamic content through our CMS.
jeph perro
Well, if you REALLY want it on a single line, you could just remove the line breaks ;)
okalex
A: 

When a script, loaded from a script src file is interpreted, its related script element exists in the document.

Don't worry about which file is which- look at every script element for an url with a query string.

kennebec