Reputation: 631
i am trying to make my own version of jfiddle. I found that it was easy to do with html but with javascript i'm having some trouble.
this is my current code:
<script>
var code;
var jscode;
function makeHTMLcode(code){
document.getElementById("body").innerHTML = code;
}
function makeJScode(jscode){
$(function() {
document.getElementById("jstester").innerHTML ="<sc"+"ript>" + jscode + "</"+"script>";
});
}
</script>
<div class="htmlTester"><textarea onkeyup="makeHTMLcode(this.value);"></textarea></div>
<div class="output">
<div style="height:100%;background-color:white; border:1px solid gray;">
<div id="body"></div>
<div id="jscode"></div>
</div>
</div>
<div class="JSTester"><textarea onkeyup="makeJScode(this.value);" ></textarea></div>
the html code goes with onkeyup to the output screen and works right away. the javascript however doesn't load its new functions. When i use the document.write function, the whole page reloads but my new made functions work. when i use the current code nothing loads.
So how can i output my new javascript functions?
Upvotes: 1
Views: 76
Reputation: 16345
What you want to set are the type
(to "text/javascript") and text
attributes.
This works if you paste it to your console on this page:
// Create an iframe and append it to your document
var iframe = document.createElement('iframe');
iframe.height = 400;
iframe.width = 600;
document.body.appendChild(iframe);
// Use this to append your HTML into the iframe
iframe.contentWindow.document.body.innerHTML =
'<div id="test">This is my iFrame</div>';
// Create an script block and append it to your iframe to sandbox it
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = "document.getElementById('test').innerHTML = 'This is cool!'";
iframe.contentWindow.document.body.appendChild(script);
Regarding the discussion in comments, I agree that you'll want to use an iframe for this, as you'll have to sandbox the JS and CSS so that there are no conflicts with the other JS & CSS controlling your page.
Upvotes: 4