tags:

views:

789

answers:

1

So I have the following code which is doing a setInterval until the iframe is available to be written to.

$( '#testdiv').append( $('<iframe id="testiframe"/>') );
var t = setInterval(function(){
 if(document.getElementById('testiframe') !== 'undefined'){
  clearInterval(t);
  $('#testiframe').contents().find('body').append('asd'); 
 }
}, 15);

Basically what happens is that jQuery creates the iframe element and loads it into the DOM. However, the iframe isn't available immediately so additional jQuery calls that are coded to happen right afterwords. With this chunk of code, it does a simple interval check until the new iframe is available, then writes 'asd' to its contents.

I've spent about an hour trying out different methods of chaining methods to the iframe creation, but nothing really works. It all seems a matter of timing. I tried $('#testiframe').live('load',function(){}); and that doesn't work at all.

So does anyone have a cleaner recommendation on this?

+4  A: 

Maybe just a regular event without live?

$('<iframe id="testiframe"/>').load(function(){
    $('#testiframe').contents().find('body').append('asd');
}).appendTo("#testdiv");
MiffTheFox
This is excellent. It hadn't occurred to me to assign the event *before* attaching it to the #testdiv element. In retrospect, I should have thought about it because I confirmed separately that you could bind the load event to the iframe without it being attached, aka:$('<iframe/>').bind('load',function(){ alert('asd'); });Gracias!
Geuis