[thelist] Javascript: Global variables in external .js?

Hassan Schroeder hassan at webtuitive.com
Sat Mar 8 17:28:01 CST 2003

Frank wrote:
> I have an external js page chock full of functions, but I find that I'm
> having to repeat some common variables, specifically div id's and such.
>         var myform = document.getElementById("myForm");
>         var mydiv= document.getElementById("myUniqueDiv");
>         var myspan= mydiv.getElementsByTagName("span");
> I've tried setting my variables at the top of the page, hoping that each
> function could make use of it, but apparently that's not the case.

> Can someone suggest how I might set them up as globals?

If they're defined as above outside a function, they're globals.

Unfortunately, they're also going to be meaningless since at the
time these particular examples are defined, the body hasn't been
written and the elements you're referencing don't exist. :-)

So you need something like:

var myform;
var mydiv;
var myspan;

function init()
	myform = document.getElementById("myForm");
	mydiv= document.getElementById("myUniqueDiv");
	myspan= mydiv.getElementsByTagName("span");

Hassan Schroeder ----------------------------- hassan at webtuitive.com
Webtuitive Design ===  (+1) 408-938-0567   === http://webtuitive.com

                           dream.  code.

More information about the thelist mailing list