My Scroll Spy

As a micro addition to my Mark Down Editor I have implemented on my site (ref: Implemented MarkDown Editor). I have now introduced a scroll spy type system to automatically scroll my preview window with the scrolling of my Mark Down Editor window. This is purely for an ease of use of the this system.

How To

First thing I need to do is find the boxes current scroll position. With jQuery this is simple thanks to the .scrollTop() method.

$('#markdown').on("scroll", function(e) {
    var _scrollValue = $(this).scrollTop();
});

Next we need to find the maximum value of that box. From those two numbers we can calculate the percentage scrolled in the box.

$('#markdown').on("scroll", function(e) {
    var _scrollValue = $(this).scrollTop();
    var _trueDivHeight = $(this).scrollHeight;
    var _divHeight = $(this).height();
    var _scrollMaxValue = (_trueDivHeight - _divHeight);
    var _scrollPercent = parseInt((_scrollValue / _scrollMaxValue)*100);
});

Now we just need to set the scroll position of my preview box to the same height percentage as my editor box. Again, this is very easy to do with jQuery.

$('#markdown').on("scroll", function(e) {
    var _scrollValue = $(this).scrollTop();
    var _scrollMaxValue = fnGetMaxScrollTopValue($(this));
    var _scrollPercent = parseInt((_scrollValue / _scrollMaxValue)*100);
    var _previewPane = $('.previewPane');
    var _previewHeight = fnGetMaxScrollTopValue(_previewPane);
    _previewPane.scrollTop(_previewHeight*(_scrollPercent/100));
});

function fnGetMaxScrollTopValue(_elem) {  
    var trueDivHeight = _elem[0].scrollHeight;
    var divHeight = _elem.height();
    return (trueDivHeight - divHeight);
}

Conclusion

Building a simple scrolling sync tool isn't complicated. In fact: it tool doesn't even require any kind of precision to be functional in this means.

If precision is required for your application, then you need to take paddings and margins into account in the fnGetMaxScrollTopValue() method.