Tuesday, July 27, 2010

'top' property of 'Window'

The top element of the DOM in Javascript has the following properties:

   1. It refers to the [object window] or the self.
   2. In case of frames or iframes, as obvious, 'top' refers to the top object that created the [i]frame i.e. the [window]
   3. But when we do a window.open(), then the top of this window refer to itself and not to the parent window.
    ps. to refer to the parent window from this newly created window there is the 'opener' property.

The following code explains it clearly...

/************************ Toping.js *******************************/

//var i = "i am at the top."
//function foo(j)
//return eval(3*j);
//alert("self: "+self.location.href+"\n"+"top: "+top.location.href);
//o = window.open("teesri.js",'win')

/************************ bottom.js ******************************/

//alert("self: "+self.location.href+"\n"+"top: "+top.location.href);
//var foo = top.foo;
//alert("top ka foo in bottom : "+ String(foo(4)));

/********************** teesri.js ********************************/

//alert("self: "+self.location.href+"\n top: "+top.location.href);

It might be a trivial concept for some, but it took long to sink in, for me!

1 comment:

  1. the document.write(); writes an iframe with the source bottom.js, but iframe is quite dynamic and thus, despite the initial commenting out "//", it was being displayed on the page, so I used the HTML comments "" and now lo! nothing is being displayed..