Codepen clone

messing around with code execution in an iframe

by Shashi Kumar Nagulakonda

HTML

<textarea id="htmleditor" placeholder="html" cols="40" rows="10">
    <h1>Title</h1>
</textarea>
<textarea id="csseditor" placeholder="css" cols="40" rows="10">h1 { color: #777; }</textarea>
<textarea id="jseditor" placeholder="js" cols="40" rows="10">(function($) { 
$(document).ready(function() {

$('body').append('why am i not in the iframe');

$('h1').addClass('underline');

});

}(jQuery));</textarea>
<button class="run-btn">Run Code</button>
<div class="render">
  <iframe id="render-frame" sandbox="allow-scripts allow-modals allow-same-origin"></iframe>
</div>

CSS

.render {
  padding: 15px 0;
}

#render-frame {
  width: 100%;
  height: 100%;
  min-height: 300px;
  background: #AAA;
}

.underline {
  text-decoration: underline;
}

JavaScript

(function($) {
  function runCode() {

    $('#render-frame').contents().find('head').html('');
    $('#render-frame').contents().find('body').html('');

    var cssValue = $('#csseditor').val();
    var htmlValue = $('#htmleditor').val();
    var jsValue = $('#jseditor').val();

    var styleValue = "<style>" + cssValue + "<\/style>";
    var scriptValue = "<script>" + jsValue + "<\/script>";
    var jqueryfornow = '<script src="https:\/\/ajax.googleapis.com\/ajax\/libs\/jquery\/1.11.3\/jquery.min.js"><\/script>';

    var head = $("#render-frame").contents().find("head");
    var content = $("#render-frame").contents().find("body");

    head.append(styleValue);
    content.prepend(htmlValue);
    content.append(jqueryfornow);
    content.append(scriptValue);
  }

  $('#render-frame').ready(runCode);
  $('.run-btn').click(runCode);

}(jQuery));