Coder
Coder

Reputation: 1129

textarea html content updated to iframe (real time) using jQuery

Is there a way I can transfer html contents entered into a textarea across to an iframe using jQuery?

I would like this to happen in real time. i.e. when the user types into the textarea it is automatically updated to the iframe without the need to refresh the page?

I have looked for an answer to this but there seems to be no clear direction so a snippet of code and explanation would be great to help me understand?

Upvotes: 1

Views: 1241

Answers (2)

fjoe
fjoe

Reputation: 1160

This seems to be a good walk-through of how to do what you want.

Here is a copy paste of the content there. As a reference as to no rely solely on a link as an answer.

Accessing an iframe from your page:

var ifrm = window.frameElement; // reference to iframe element container
var doc = ifrm.ownerDocument; // reference to container's document
var form = doc.forms[0]; // reference to first form in container document

jQuery Version:

$("#myiframe").contents().find("#myForm");

Accessing a parent from your iframe:

// reference to first form in parent document
var form = parent.document.forms[0];
// or, using form id instead
var form = parent.document.getElementById('myForm');

jQuery Version:

$('#myForm', window.parent.document).html();

There is a caveat to this though XSS: Which basically means you can only do these things if the site domain and the iframe domain are the same.

There are workarounds for this though: If you use your web server to get the content of another domain and server it as your own then the browser will not complain about XSS.

To directly answer your question the jQuery below this should work from the parent page using the jQuery contents function (see last demo on page):

$(function () {
    $("#myTextArea").on("change keyup paste", function () {
        $("#myiframe").contents().find("html").html($("#myHtmlDiv").val());
    });
});

I have updated the above jQuery example so it should be working now but if not here is a tested JavaScript approach seemed to do the trick:

$(function () {
    $("#myTextArea").on("change keyup paste", function () {
        var doc = document.getElementById("myiframe").contentWindow.document;
        doc.open();
        doc.write($(this).val());
        doc.close();
    });
});

Upvotes: 1

Vickar
Vickar

Reputation: 953

Just 2 changes to @fjoe's solution, and the jQuery code worked a 100%.

$(function () {
    $("#myTextArea").on("change keyup paste", function () {
        $("#myiframe").contents().find("html").html($(#myTextArea).val());
    });
});

change the parameters of

  1. find("#myHtmlDiv") to find("html")

  2. and, html(this).val()) to html($("#myHtmlDiv").val())

Upvotes: 1

Related Questions