Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

better way to create dynamic iframes in jQuery?

Tags:

jquery

iframe

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?

like image 995
Geuis Avatar asked Nov 10 '09 00:11

Geuis


1 Answers

Maybe just a regular event without live?

$('<iframe id="testiframe"/>').load(function(){
    $('#testiframe').contents().find('body').append('asd');
}).appendTo("#testdiv");
like image 177
MiffTheFox Avatar answered Sep 22 '22 01:09

MiffTheFox