1

I was trying to make a Code Playground like Tinkerbin.

It basicaly takes the CSS / HTML / Javascript Code out of different Textareas and injects it into an Iframe. It also should instantly update the Iframe.

However I'm a little bit stuck with injecting the Javascript.


See, what I have done thus far:

(function() {
    $('.grid').height( $(window).height() );    

    var contents = $('iframe').contents(),
        body = contents.find('body'),
        styleTag = $('<style></style>').appendTo(contents.find('head'));

    $('textarea').keyup(function() {
        var $this = $(this);
        if ( $this.attr('id') === 'html') {
            body.html( $this.val() );
        } 
        if ( $this.attr('id') === 'css') {
            styleTag.text( $this.val() );
        }
    });

})();

This does inject the CSS and HTML, but not the Javascript.

I tried adding

        scriptTag = $('<script></script>').appendTo(contents.find('head'));

and

        if ( $this.attr('id') === 'javascript') {
            scriptTag.text( $this.val() );
        }

But it didn't work


Somebody can help me out?

Noah Wetjen
  • 1,695
  • 2
  • 17
  • 30
  • Unrelated, but you should take a look at this: http://stackoverflow.com/questions/8004001/how-does-jsfiddle-allow-and-execute-user-defined-javascript-without-being-danger – irrelephant Aug 15 '12 at 07:12

1 Answers1

1

I think you may need to inject the script tag and content at the same time, because inserting the <script> tag will cause the broswer to run the script. if the script content is inserted later, it may not be run, but I am not sure. try it like this:

$('<script></script>')
      .text($('theinputselectorhere').val())
      .appendTo(contents.find('head'));
bingjie2680
  • 7,643
  • 8
  • 45
  • 72