Kirk Woll
Nov 29
Synchronizing scroll bars between an editor and its preview

After using the helpful tips provided on this StackOverflow question on how to synchronize the scroll bars between an editor (such as for markdown) and a preview panel, I cleaned it up to make it more re-usable.

Just include this anywhere you define your scripts (I'd recommend a script declared in your head so you don't have to mess with window.onload silliness.

function synchronizeScroll(editorId, previewId) {
    function syncScroll(from, to) {
        const scrollFrom = from.scrollHeight - from.clientHeight;
        const scrollTo = to.scrollHeight - to.clientHeight;

        if (scrollFrom < 1) {
            return;
        }

        const percentage = (from.scrollTop / scrollFrom) * 100;

        to.scrollTop = (scrollTo / 100) * percentage;
    }

    window.addEventListener("load", () => {
        var currentScrollEvent, timer;

        var editor = document.getElementById(editorId);
        var preview = document.getElementById(previewId);

        function bindScrollEvent(from, to) {
            from.addEventListener("scroll", () => {
                if (currentScrollEvent === to) {
                    return;
                }
                clearTimeout(timer);
                currentScrollEvent = from;
                syncScroll(from, to);
                timer = setTimeout(() => currentScrollEvent = null, 200);
            });
        }

        bindScrollEvent(editor, preview);
        bindScrollEvent(preview, editor);
    });
}

Usage:

    synchronizeScroll("post-body", "post-body-preview");

This assumes that the editor (a textarea for me has an id of post-body and the preview div (with an overflow-y) has an id of post-body-preview.

Note your comment will be put in a review queue before being published.