13

How do I use the refresh function from CodeMirror 2?

refresh()

If your code does something to change the size of the editor element (window resizes are already listened for), or unhides it, you should probably follow up by calling this method to ensure CodeMirror is still looking as intended.

I want to refresh all textareas after a link is clicked

I tried

  $('.CodeMirror').each(function(){
    getElementById($(this).attr('id')).refresh();
  });

but it doesn't work....

Alex
  • 66,732
  • 177
  • 439
  • 641
  • http://stackoverflow.com/questions/40512977/codemirror-horizontal-split-view-and-resize-with-mouse-drag-html-live-editor – STEN Nov 12 '16 at 17:14

2 Answers2

23

When you instantiate the CodeMirror instance, it is placed as a property on the wrapper div.

$('.CodeMirror').each(function(i, el){
    el.CodeMirror.refresh();
});

The above snippet does not recreate the editor, but instead uses the existing one.

Jonathan Schneider
  • 26,852
  • 13
  • 75
  • 99
  • Is there anyway to decide, which CodeMirror element I selected, e.g. can I select a single CodeMirror field? `el` seems to not store any name data. Selecting the CodeMirrors this way would be nice, since it doesn't require to (globally) store the Codefields to enter new text. – lakerz Jun 22 '15 at 15:31
  • Stupid me - of course I can preselect the containing div and then look for `.CodeMirror`. But if I know that I'll only select one, is `each` the right function, or are there others, more preferable? – lakerz Jun 22 '15 at 15:33
  • Use each. Your single selection is just a special case of selecting multiple elements. – Jonathan Schneider Jun 22 '15 at 17:30
9

The refresh method (just like all other CodeMirror methods) does not live on the DOM node, but on the instance object that's returned when you create the editor (by calling CodeMirror or CodeMirror.fromTextArea). So you'll have to store those somewhere for this to work.

Marijn
  • 8,691
  • 2
  • 34
  • 37
  • tx, I used stored all codemirror instances inside a array, then iterated the array with refresh() on each instance – Alex Mar 23 '11 at 07:53