Search code examples
htmlcodemirror

Using CodeMirror to highlight text in textarea?


I have a textarea that on button click will be filled with the contents of a certain file. I am trying to implement CodeMirror that will automatically highlight the syntax of the code that is loaded into the textarea.


Solution

  • You have to make sure you have the proper mode js files loaded (look at the external resources in the fiddle) and then it's as simple as a setValue call.

    http://jsfiddle.net/blaird/mssrahz1/1/

    var myCodeMirror = CodeMirror.fromTextArea(document.getElementById("editor"), {
        lineNumbers: true,
        mode: "htmlmixed"
    });
    
    var loadButton = document.getElementById("load");
    loadButton.onclick = function () {
        // here you'd load your file and then call setValue with the result
        myCodeMirror.setValue("<div>Hi There</div>\n<ul>\n\t<li>one</li>\n</ul>");
    };