Codemirror editor is not loading content until clicked

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:

codeMirrorRef.setValue(content);
setTimeout(function() {
    codeMirrorRef.refresh();
},1);

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


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.


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));

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.