Dynamically Adding HTML into an iFrame - Javascript

496 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

check out this post: addEventListener to iFrame

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

0
On
$('.' + 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.