1

I'm attempting to dynamically create an iFrame and add HTML into it from the current document. The iFrame gets created successfully, but when the function gets to the point where it needs to add the HTML in, it doesn't do it.

Here's my code:

function createiFrame(min, max, key) {
    console.log("Max-Width", max);

    //CREATING A CLASS FOR THE IFRAME
    var iframeClass = key + "-" + max;
    //var path = window.location.pathname;
    //var page = path.split("/").pop();

    //ADDING AN IFRAME INTO THE DOCUMENT AND ADDING ON THE CLASS
    $(document).ready(function() {
        $('<iframe>', {
            width: max
        }).addClass(iframeClass).prependTo('body');
    });


    var requiredHTML = document.getElementById('container').innerHTML;
    console.log("RequiredHTML", requiredHTML);

    //ADDING THE COLLECTED HTML INTO THE IFRAME -- THIS IS WHERE 
    //IT STOPS WORKING
    $('.' + iframeClass).ready(function() {
        console.log("iFrame ready");
        $('.' + iframeClass).contents().find('body').html("<p>Testing it out</p>");
    });

    var $head = document.getElementsByTagName('head')[0].innerHTML;
    $(document).ready(function() {
        $('.' + iframeClass).contents().find('head').append($head);
    });


}

EDIT

I've realised this problem is occurring because when I try to run that code, the DOM isn't ready yet.

So new question;

How do I get the DOM ready?

Rafill
  • 235
  • 1
  • 3
  • 14
  • This was answered here: http://stackoverflow.com/questions/19374524/use-jquery-to-insert-html-into-an-iframe-body-tag – FroboZ Jun 10 '15 at 13:54
  • @ChristopherKarlsson thanks for the link, but that question is talking about nested iFrames, and the answer gives the same line of jQuery that I have in my code, but it doesn't work – Rafill Jun 10 '15 at 14:55
  • Does this help? http://stackoverflow.com/questions/205087/jquery-ready-in-a-dynamically-inserted-iframe – Rick S Jun 10 '15 at 15:50
  • 1
    You can't attach the jQuery [`.ready()`](http://api.jquery.com/ready/) handler to just anything. The only target it works on is the current document. You will have to use the native `load()` event instead. – Dave Jun 10 '15 at 15:57

2 Answers2

0

check out this post: addEventListener to iFrame

you need to use $('#myIFrame').load(function(){ ....

Community
  • 1
  • 1
0
$('.' + iframeClass).ready(function() {
    ...
}

Doesn't work because an iframe being ready doesn't trigger the Event 'DOMContentLoaded' which .ready() is waiting for. You'll need to refer directly to a document, which will then trigger the DOMContentLoaded event. This should work based on that.

$(iframeClass document).ready(function() {
    ...
}

I will stress though that this isn't something that I've tried before, but it seems like it's just a matter of which document you're referring to.

Alex Deas
  • 15
  • 5