Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem to write something into one window from another via JS 1

Status
Not open for further replies.

cadoltt

Programmer
Jun 9, 2005
85
CA
Hello everybody,


Write something into one window from another with JS


I've encountered a strange thing (hope the thing is strange just to me). Here is a simplified version of my application.

There are two pages, I call them window1 and window2:

Code:
<HTML>
  <head>
    <title>Window_1</title>
    <script language="JavaScript" src="w1.js"> </script>
  </head>

  <body>

    <H1>Window_1</H1>

    <input type="button" value="Open window_2" onclick="open_wnd2()">

  </body>
</html>


Code:
<HTML>
  <head>
    <title>Window_2</title>
  </head>

  <body>

    <H1>Window_2</H1>

    <div id="div1" 
      style="position:relative;
      left:1px;
      top:1px;
      width:200px;
      height:100px;">
    </div>

  </body>
</html>


and a simple javascript file:

Code:
var objWnd2;
var objDiv;


function open_wnd2()
 {
  objWnd2 = window.open('w2.htm','wnd2','width=600,height=500,menubar=no,status=no,location=no,toolbar=no,scrollbars=no');

  //alert("window is created");

  objDiv = objWnd2.document.getElementById("div1");

  objDiv.innerText="in div";

 }


When I click the button on the first page the open_wnd2() function is being called which opens the second page (window). After the opening the function tries to write some text into the div element existing on the second page.

Pretty simple? But the strange thing is that sometimes it works the other times doesn't. The window always gets open but the writing into the div may fail. If I activate the alert "window is created" (now it's commented out) then iw works most of the times (not all!), when it's commented most of the times it doesn't work.

I feel that I am doing something stupid but I can't figure out what exactly. Can anyone tell me what the problem is?


Thanks,
Alex
 
This is the problem:

The popup window needs time to load entirely before you can refer to objects in the window.


Try this as a solution:

Code:
function open_wnd2()
 {
  objWnd2 = window.open('test2.html','wnd2','width=600,height=500,menubar=no,status=no,location=no,toolbar=no,scrollbars=no');

  //alert("window is created");
  
  objDiv = objWnd2.document.getElementById("div1");
  [!]while (!objDiv) {
     objDiv = objWnd2.document.getElementById("div1");
  }[/!]
  objDiv.innerText="in div";

 }



[monkey][snake] <.
 
Monksnake,

It works now, thanks a lot!

Alex
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top