Arcticfoxx
Arcticfoxx

Reputation: 451

Javascript edit iframe when content of textarea

<script type="text/javascript">
function change() {
document.getElementById('target').getElementsByTagName('html').getElementsByTagName('body').innerHTML = document.getElementById('src').value;
}
</script>

<textarea id="src" onchange="change();"></textarea><br/>
<iframe id="target"></iframe>

This is my code and I don't understand why it isn't working. No jQuery please. I know things like this exist for example htmledit squarefree I have tried frame instead of iframe and that hasn't worked either

Upvotes: 0

Views: 3639

Answers (2)

JJJ
JJJ

Reputation: 490

<script>
// Tested on Chrome 24 onchange is if you use backspace etc. use keyup for text
// It replaces \n with <br/> if you don't want that wrap the content in a <pre> tag
    document.getElementById("src").onchange=document.getElementById("src").onkeyup=function(){
        document.getElementById('target').contentDocument.getElementsByTagName('body')[0].innerHTML = this.value.replace('\n','<br/>');
    }
</script>

Upvotes: 0

davehale23
davehale23

Reputation: 4372

Is this what you are looking for? First I am using onkeyup on the textarea, I don't think that textarea has an onchange event. Then I am grabbing the iframe using two different methods depending on the browser and then populating the iframe with the text from the textarea.

<script type="text/javascript">
function change() {
  var iFrame =  document.getElementById('target');
   var iFrameBody;
   if ( iFrame.contentDocument ) 
   { // FF
     iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
   }
   else if ( iFrame.contentWindow ) 
   { // IE
     iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
   }
    iFrameBody.innerHTML = document.getElementById('src').value;
}
</script>

<textarea id="src" onkeyup="change();"></textarea><br/>
<iframe id="target"></iframe>​

Upvotes: 3

Related Questions