Codemirror editor is not loading content until clicked

Codemirror editor is not loading content until clicked

I am using codemirror 2 and its working fine except that the editor’s set value doesn’t load into the editor until I click the editor and it becomes focused.
I want the editor to show the content of itself without it having to be clicked. Any ideas?
All of the codemirror demos work as expected so I figured maybe the textarea isn’t focused so I tried that too.
$(“#editor”).focus();
var editor = CodeMirror.fromTextArea(document.getElementById(“editor”), {
mode: “text/html”,
height: “197px”,
lineNumbers: true
});

Solutions/Answers:

Solution 1:

You must call refresh() after setValue(). However, you must use setTimeout to postpone the refresh() to after CodeMirror/Browser has updated the layout according to the new content:

this.codeMirrorInstance.setValue(content);
var that = this;
setTimeout(function() {
    that.codeMirrorInstance.refresh();
},1);

It works well for me. I found the answer in here.

Solution 2:

I expect you (or some script you loaded) is meddling with the DOM in such a way that the editor is hidden or otherwise in a strange position when created. It’ll require a call to its refresh() method after it is made visible.

Related:  Backbone.js model with collection

Solution 3:

Just in case, and for everyone who doesn’t read the documentation carefully enough (like me), but stumbles upon this.
There’s an autorefresh addon just for that.

You need to add autorefresh.js in your file.
Now you can use it like this.

var editor = CodeMirror.fromTextArea(document.getElementById("id_commentsHint"), {
  mode: "javascript",
  autoRefresh:true,
  lineNumbers: false,
  lineWrapping: true,

});

works like a charm.

Solution 4:

I happen to be using CodeMirror within a bootstrap tab. I suspected the bootstrap tabs were what was preventing it from showing up until clicked. I fixed this by simply calling the refresh() method on show.

var cmInstance = CodeMirror.fromTextArea(document.getElementById('cm'), {
    lineNumbers: true,
    lineWrapping: true,
    indentUnit: 4,
    mode: 'css'
});

// to fix code mirror not showing up until clicked
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function() {
    this.refresh();
}.bind(cmInstance));

Solution 5:

Something worked for me.

$(document).ready(function(){
                var editor = CodeMirror.fromTextArea(document.getElementById("code2"), {
                     //lineNumbers: true,
                      readOnly: true,
                      autofocus: true,
                     matchBrackets: true,
                     styleActiveLine: true
                 });
                 setTimeout(function() {
                     editor.refresh();
                    }, 100);

        });

Solution 6:

The 5.14.2 version of codemirror addresses this fully with an add on. See this answer for details.

Related:  How can I use backslashes (\) in a string?