Wait for iframe to load in JavaScript

Bill Dawes picture Bill Dawes · Sep 23, 2009 · Viewed 58k times · Source

I am opening an iframe in JavaScript:

righttop.location = "timesheet_notes.php";

and then want to pass information to it:

righttop.document.notesform.ID_client.value = Client;

Obviously though, that line isn't going to work until the page has fully loaded in the iframe, and that form element is there to be written to.

So, what is the best/most efficient way to address this? Some sort of timeout loop? Ideally I would really like to keep it all contained within this particular script, rather than having to add any extra stuff to the page that is being opened.

Answer

Crescent Fresh picture Crescent Fresh · Sep 23, 2009

First of all, I believe you are supposed to affect the src property of iframes, not location. Second of all, hook the iframe's load event to perform your changes:

var myIframe = document.getElementById('righttop');
myIframe.addEventListener("load", function() {
  this.contentWindow.document.notesform.ID_client.value = Client;
});
myIframe.src = 'timesheet_notes.php';

Again, this is all presuming you mean iframe, not framesets.