CodeMirror - Is it possible to scroll to a line so that it is in the middle of window?

Martin Vseticka picture Martin Vseticka · May 13, 2012 · Viewed 10.6k times · Source

I'm highlighting lines of HTML code in CodeMirror and I want to add an anchor that scroll CodeMirror editor to a given line.

I can scroll to a line X via setCursor method. But I would like to have the line X in the middle of CodeMirror window. Can I do that? I studied the API and demos but with no luck.

Thanks!

Answer

Eric Grivilers picture Eric Grivilers · May 9, 2014

This one should work:

var editor = CodeMirror.fromTextArea(...);

function jumpToLine(i) { 
    var t = editor.charCoords({line: i, ch: 0}, "local").top; 
    var middleHeight = editor.getScrollerElement().offsetHeight / 2; 
    editor.scrollTo(null, t - middleHeight - 5); 
}