Geuis
Geuis

Reputation: 42317

better way to create dynamic iframes in jQuery?

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?

Upvotes: 11

Views: 14900

Answers (1)

MiffTheFox
MiffTheFox

Reputation: 21575

Maybe just a regular event without live?

$('<iframe id="testiframe"/>').load(function(){
    $('#testiframe').contents().find('body').append('asd');
}).appendTo("#testdiv");

Upvotes: 26

Related Questions