1

I have a <DIV> and a <TEXTAREA>, the problem is that the element (that will receive synchronization) scrolls more than expected, rather than with the percentage.

So far I have managed to do this:

function syncScroll(from, to)
{
    var sf = from.scrollHeight - from.clientHeight,
        st = to.scrollHeight - to.clientHeight;

    if (sf < 1) {
        return;
    }

    var p = (sf / 100) * from.scrollTop;

    to.scrollTop = (st / 100) * p;
}


window.onload = function() {
    var currentScrollEvt, timer;

    var editor  = document.querySelector(".editor");
    var preview = document.querySelector(".preview");

    preview.innerHTML = editor.value;

    editor.onscroll = function() {
        if (currentScrollEvt === "preview") {
             return;
        }

        clearTimeout(timer);

        currentScrollEvt = "editor";

        syncScroll(editor, preview);

        timer = setTimeout(function() {
            currentScrollEvt = null;
        }, 200);
    };

    preview.onscroll = function() {
        if (currentScrollEvt === "editor") {
             return;
        }

        clearTimeout(timer);

        currentScrollEvt = "preview";

        syncScroll(preview, editor);

        timer = setTimeout(function() {
            currentScrollEvt = null;
        }, 200);
    };
};
html, body {
    padding: 0;
    margin: 0;
    height: 100%;
}

* {
    box-sizing: content-box;
}

body {
    display: flex;
}

.editor, .preview {
    flex: 1;
}

.preview {
    background-color: #f00;
    overflow: auto;
    float: right;
}
<textarea class="editor">
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
</textarea>

<div class="preview"></div>

1 Answer 1

3

Your percentage calculation is wrong, try this instead:

    var p = from.scrollTop / sf * 100;
1
  • Work fine, thanks! :D (2min for accept, limitation from stackoverflow)
    – Reptile
    Aug 13, 2016 at 20:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.