Shaun Mccran

My digital playground

28
J
A
N
2011

Passing variables to js files inline

Ever wanted to pass a variables to a javascript file within the code?

You can declare JavaScript variables globally, but in this case a non technical person was editing the sites code base, so getting them to construct

JavaScript variables was going to be an issue. How about passing them through within the script tag?

Construct your Javascript script code as usual, but append your value on the end, as per below. Also give the script tag an id value.

view plain print about
1<s/cript src="../../javascript.js?passedvalue" id="javascript_identifier"></s/cript>

Next inside the JavaScript file read the src attributes using JQuery and the id of the script tag. Below I've split the returned string at the '?'

character and created a array out of it. Pick up the first value (not the zero value) and it will give you the text string after the question mark.

You could pass many values like this, and use the split() method to turn them into Arrays and loop through them.

view plain print about
1var scriptsrc = $('#javascript_identifier').attr('src');
2        scriptsrc = scriptsrc.split('?');
3        scriptsrc = scriptsrc[1];
4        alert('scriptsrc = ' + scriptsrc);

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
david's Gravatar Use the data-* attributes. Your html will not validate but it requires less typing and jQuery has a method to fetch those values.
# Posted By david | 30/01/2011 10:04
Shaun's Gravatar @david Thanks, I didn't think of using that, I'll check out the JQuery method of getting the values.
# Posted By Shaun | 30/01/2011 16:31
Back to top