Search code examples
javascripthtmlcsscodemirror

How do I integrate Codemirror library in HTM file?


I have tried no of times how can I do this, unfortunately I could not figure out how do I integrate the codemirror library in HTML file.

I have one HTML file and I downloaded the codemirror. I also included the lib folder in my html directory but when I see it in the browser the codemirror editor is not been created.

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Web Editor</title>
<!-- Create a simple CodeMirror instance -->
<link rel="stylesheet" href="lib/codemirror.css">
<script src="lib/codemirror.js"></script>
<script>
  var editor = CodeMirror.fromTextArea(myTextarea, {
    lineNumbers: true
  });
</script>
</head>
    <body>
        <table>
            <tr>
                <td>
                    <div class="tag">HTML (Body)</div>
                    <div id="html" class="content" contenteditable></div>
                </td>
                <td>
                    <div class="tag">CSS</div>
                    <div id="css" class="content" contenteditable></div>
                </td>
            </tr>
            <tr>
                <td>
                    <div class="tag">JavaScript</div>
                    <div id="js" class="content" contenteditable></div>
                </td>
                <td>
                    <div class="tag">Output</div>
                    <iframe id="output">Hello</iframe>
                </td>
            </tr>
        </table>
    </body>
</html>

How can I create a sample codemirror editor ? Thanks you.


Solution

  • You are supposed to first define a myTextarea in your codemirror instance. Just include a textarea in your html file like this,

    <textarea id="myCode"></textarea>
    

    Now, define myTextarea like this,

    var myTextarea = document.getElementById("myCode");
    

    Hence, finally your file would look like this,

    <body>
        <textarea id="myCode"></textarea>
    
        <script type="text/javascript">
          window.onload = function() {
            var myTextarea = document.getElementById("myCode");
            editor = CodeMirror.fromTextArea(myTextarea, {
              lineNumbers: true
            });
          };
        </script>
    </body>
    

    Here is the working fiddle http://jsfiddle.net/dsaket/tqL7z213/1/.

    Also, for further queries, you should check out the demo files provided by codemirror.