Search code examples
javascripthtmleditorlive

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


Solution

  • 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>​