Question

I'm building a live-preview editor with CodeMirror. I need to determine if the CodeMirror editor is scrolled to the very bottom so that I can scroll the preview to the bottom as well.

How can I determine this?

Was it helpful?

Solution

You need the scroller element in codeMirror, then bind a function on scroll event.

jsfiddle

var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
    mode: "text/html"
});    

var scrollElement = editor.getScrollerElement();
  console.log(scrollElement )
  $(scrollElement).bind('scroll', function(e) {
      var elem = $(e.currentTarget);
      if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) {
          console.log("bottom");
      }      
  });

OTHER TIPS

Had to make some minor adjustments to aljordan82's solution:

var editor = CodeMirror.fromTextArea(document.getElementById('post'), {
    'mode': 'gfm',
    'lineNumbers': true,
    'theme': 'default',
    'lineWrapping': true,
});

var $preview = $('#preview-div');
var $scroller = $(editor.getScrollerElement());

$.fn.scrollHeight = function() {
    return this[0].scrollHeight;
};

var atBottom = $scroller.scrollHeight() - $scroller.scrollTop() - $scroller.outerHeight() <= 0
    && $preview.scrollHeight() - $preview.scrollTop() - $preview.outerHeight() <= 0;
$preview.html(html);
if (atBottom) {
    $preview.scrollTop($preview.scrollHeight());
}

The numbers weren't coming out quite equal on my preview div, so I did <= 0 instead. (2px off, maybe due to borders?)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top