Guilherme Nascimento Guilherme Nascimento - 3 months ago 22
CSS Question

How sync two scrollbars with Javascript pure?

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>




Answer

Your percentage calculation is wrong, try this instead:

    var p = from.scrollTop / sf * 100;