Question

I am creating my own code for a live html/js/jquery/css editor. This is the code to simply inject css, html, and javascript(specifically jquery). The css and html work fine, but no matter what i do ican't seem to get the jquery or javascript working... heres my code:

var contents = $('iframe').contents(),
    body = contents.find('body'),
    styleTag = $('<style></style>').appendTo(contents.find('head'));
var makeScript = $('<script class type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"><\/script>');
var scriptTag = $('<script type="text/javascript"><\/script>').appendTo(contents.find('head'));
$ ('textarea').keyup(function() {
    var ths = $(this);
    if (ths.attr('id') === 'html') {
        body.html(ths.val());
    }
    else if (ths.attr('id') === 'css') {
        // it had to be css
        styleTag.text(ths.val());
    }
    else {
        makeScript.appendTo(contents.find('head'));
        scriptTag.text(ths.val());
    }
});

here's my html:

<div>
    <form>
        <h2>HTML</h2>
        <textarea id="html"></textarea>
        <h2>CSS</h2>
        <textarea id="css"></textarea>
        <h2>JS</h2>
        <textarea id="js"></textarea>
    </form>
</div>
<div id="output" style="height: 487px;">
    <iframe src="about:blank"></iframe>
</div>

if any one sees something wrong with my code please help, and if you answer please explain your solution, rather that just typing a block of code....and I tried entering jquery and regular javascript into the html textarea (within a script tag but it still didn't work).

Was it helpful?

Solution

First I think you spelled this wrong. It should be scriptTag.text(this.val());

I think your issue goes deeper than that. It is my understanding that when you inject a script tag into the dom it gets evaluated immediately but you are waiting to put the actually code in AFTER it has been already added to the page. Reorder it.

scriptTag = $("<script type='text/javascript'>" + this.val() + "</script>")
   .appendTo($('iframe').contents().find('head'));

Note I had to bring out the selector contents because it was in the scope of a different function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top