Search code examples
javascriptjqueryhtmlcodemirror

How to output result of codemirror in iframe?


I am trying to make a HTML code player in which you enter html and get result in iframe. it works good if i only use textarea and output in iframe. but if i use code mirror and try putting coremirror value into iframe it shows me code in iframe instead of showing me result.

<!DOCTYPE html>
<html>

  <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script src="codemirror/codemirror/lib/codemirror.js"></script> 
  <link rel="stylesheet" href="codemirror/codemirror/lib/codemirror.css"/> 
  <link rel="stylesheet" href="codemirror/codemirror/theme/neo.css">

  <script src="codemirror/codemirror/mode/javascript/javascript.js"></script>   
  <script src="codemirror/codemirror/mode/css/css.js"></script>  
  <script src="codemirror/codemirror/mode/htmlmixed/htmlmixed.js"></script>  

   <script src="codemirror/codemirror/addon/hint/show-hint.js"></script>
   <script src="codemirror/codemirror/addon/hint/css-hint.js"></script>
   <link rel="stylesheet" href="codemirror/codemirror/addon/hint/show-hint.css">

  <style>
  body {
    background-color: #eee;
}
iframe{height:600px;width:400px}
</style>
  </head>

  <body>  
      <div id="codeeditor"></div>
      <iframe>Example</iframe>
      <button>RUN</button>
    <script>
       var editor = CodeMirror(document.getElementById("codeeditor"), {
    value: "<html><body><h1>Helloworld</h1></body></html>",
    mode: "css",
    theme: "neo",
    extraKeys: {"Ctrl-Space": "autocomplete"}
});
     $("button").click(function(){
          $("iframe").contents().find("body").html($("#codeeditor").html());
     })


    </script>
  </body>

</html>

Solution

  • Do not take editor contents using jQuery, instead use codemirror method getValue like this:

    $("button").click(function(){     
      $("iframe").contents().find("body").html(editor.getValue());
    })