View Full Version : Scoping variables with multiple frames

06-15-2007, 11:49 PM

I've defined a parent document that has only one iframe. This iframe has a reference to an external javascript file. The problem is that the list of functions in this external .js file has references to elements in the iframe, but they do not work. So if I try to access a <DIV NAME="div1" ID="div1" > in the iframe using this javascript, I get nothing. The code inside the function would look like this:


where, hopefully, document refers to the local IFRAME. I would think that since the .js file is referenced inside the IFRAME's HEAD tags, that it would look in that document for its elements, right?

Unfortunately I just get null values.

Any assistance is appreciated!


Mr J
06-16-2007, 12:34 AM
Are you trying to reference the div in the iframe from the parent?

06-16-2007, 01:15 AM
Hello, Mr J,

In the parent I set the mouse event as an attribute on the body of the document in the iframe.
Like this:


That mouse event calls the function in the .js file for a div in the iframe. This part works -- the function definitely is being called from the mouse event that occurs inside the iframe.

Like this:

function setStartDraw(e,id) {

var currentElement=document.getElementById(id);

debug("element: " + document.getElementById(id));return false;
//^^^^element is null, sad to say

id in this case refers to the div in the iframe document this same js code is in!

The function does not seem to know the elements in the document of the iframe, even when referenced by "id".


06-16-2007, 01:25 AM
The problem could be that since the handler is set from the parent, the code runs in the context of the parent.

Try this:

var currentElement=window.frames["map_target"].document.getElementById(id);If window doesn't work, try replacing it with parent.

BTW, is there any special reason you don't set the handler from the iframe itself?

06-16-2007, 01:37 AM
Hello, Glenn,
parent did not seem to make any difference. The reason I'm setting the event handler there is because I put the control buttons for the map (zoom, pan, draw selection box, etc.) in the main document, but the map is inside the frame, along with the code that does the drawing, panning, etc.
This may not be the best design, but I'm too new to this to know scoping issues that well. I'm trying to save space for the map and just put the map controls on the border outside, plus I have to translate lat/long coordinates into a frame of reference on the map itself. I thought an iframe was the way to go, but it is a real pain. I guess I could try to get rid of the iframe and put the map in the main doc itself. I didn't realize iframes were that much work!

Thanks for your post,


06-16-2007, 04:19 AM
Ohhhhweeee -- I found the bug. Really dumb user error. Disregard post!