0

I am making a simple code editor. Two panels - One to write the code and another to display the output.

For Html and Css the below code works fine. But for javascript which has to be executed on page load this doesn't work. When the Update Page button is clicked the input code must be rendered on the display frame. Like a simple alert on page load wont work.

My question is how should I imitate the frame reload action. I don't have any value for src attribute of the frame so cannot reload it.

<html>
<body>
<script>
function update()
{
   var x = document.getElementById('mycode').value;
   frames['display'].document.documentElement.innerHTML = x;
}
</script>

<input onclick="update();" type="button" value="Update page">
<textarea id="mycode"></textarea>
<iframe id="display"></iframe>

</body>
</html>

When this code is entered in the textarea, it wont work in the frame.

<html>
<script>alert(123);</script>
</html>

But for normal html,css it works. How should I make javascript code like above which only gets executed during pageload work in the frame?

Editor works for this kind of event driven javascript

<html>
<input onclick="alert(123);" type="button" value="Works">
</html>
  • javascript can access only local ifames (which has been created by your code or loaded from the same server). – Epsil0neR Jan 03 '14 at 19:18
  • @Epsil0neR When the Update Page button is clicked the code from the textarea is loaded into the frame. –  Jan 03 '14 at 19:21

1 Answers1

0

Use

<input type="button" id = "btn" value="Update Page" />
<textarea id="mycode"></textarea>
<iframe id="display"></iframe>

as your HTML and

document.getElementById('btn').onclick = function()
{
    var x = document.getElementById('mycode').value;
    document.getElementById('display').contentDocument.write(x);
}

as your Javascript.

contentDocument.write is used to write an iframe's innerHTML. See set innerHTML of an iframe

DEMO

Community
  • 1
  • 1
Cilan
  • 13,101
  • 3
  • 34
  • 51