Skip to content

Create CodeMirror editor from a TextArea

In this post we are going to see how to create a simple CodeMirror editor from a TextArea in HTML. CodeMirror is a rich text editor implemented in JavaScript for the browser. It is used for editing code, and comes with over 100 language modes and various plugins that implement more advanced editing functionality.

Let’s start with a simple HTML.

 <textarea id="code" name="code">

Let’s convert this textarea into a CodeMirror editor. First of all, download CodeMirror source code from this link and extract codemirror.css and codemirror.js to the root directory of your project.

Import the CodeMirror css and js to your html.

  <link rel="stylesheet" href="codemirror.css">
  <script src="codemirror.js"></script>

Convert the textarea into Codemirror editor.

 var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
            styleActiveLine: true,
            lineNumbers: true,
            matchBrackets: true
        });

As simple as that.

Spice it up with a bit of css.

 .CodeMirror {
        margin: 0 auto;
        margin: 2%;
        border: 4px solid #3a3a3a;
        font-size: 15px;
        font-family: 'Viga', sans-serif;
        border-radius: 1px;
        line-height: 1.2em;
        height: 3.6em;
    }

You will get an output like this.

See also  Add Google Fonts to your web page

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.