I have two boxes with the same content but they are of different dimensions and I synchronise scrolling between them so if you scroll one the other follows and vice versa, the problem is that once you scroll down it seams to continue scrolling on its own, is there any way to fix this?
Codepen: https://codepen.io/rgbskills/pen/JjrRpVN?editors=0010
let master = document.getElementById('text');
let slave = document.getElementById('text2');
const masterScrollHeight = master.scrollHeight;
const masterClientHeight = master.clientHeight;
const masterHeight = masterScrollHeight - masterClientHeight;
const slaveScrollHeight = slave.scrollHeight;
const slaveClientHeight = slave.clientHeight;
const slaveHeight = slaveScrollHeight - slaveClientHeight;
const handleScrollMaster = (e) => {
const newMasterScrollTop = e.currentTarget.scrollTop;
const percentageMasterDone = newMasterScrollTop / masterHeight;
const newSlaveScrollTop = Math.ceil(percentageMasterDone * slaveHeight);
slave.scroll({
top: newSlaveScrollTop
})
}
const handleScrollSlave = (e) => {
const newSlaveScrollTop = e.currentTarget.scrollTop;
const percentageSlaveDone = newSlaveScrollTop / slaveHeight;
const newMasterScrollTop = Math.ceil(percentageSlaveDone * masterHeight);
master.scroll({
top: newMasterScrollTop
})
}
master.addEventListener("scroll", handleScrollMaster);
slave.addEventListener("scroll", handleScrollSlave);
I'm not sure why this fixes my problem but here is my solution:
I simply removed the Math.ceil from one of the event listener funstions.
Codepen: https://codepen.io/rgbskills/pen/JjrRpVN?editors=0010
let master = document.getElementById('text');
let slave = document.getElementById('text2');
const masterScrollHeight = master.scrollHeight;
const masterClientHeight = master.clientHeight;
const masterHeight = masterScrollHeight - masterClientHeight;
const slaveScrollHeight = slave.scrollHeight;
const slaveClientHeight = slave.clientHeight;
const slaveHeight = slaveScrollHeight - slaveClientHeight;
const handleScrollMaster = (e) => {
const newMasterScrollTop = e.currentTarget.scrollTop;
const percentageMasterDone = newMasterScrollTop / masterHeight;
const newSlaveScrollTop = Math.ceil(percentageMasterDone * slaveHeight);
slave.scroll({
top: newSlaveScrollTop
})
}
const handleScrollSlave = (e) => {
const newSlaveScrollTop = e.currentTarget.scrollTop;
const percentageSlaveDone = newSlaveScrollTop / slaveHeight;
// for some reason if I apply Math.ceil here it will cause an infinite scroll
const newMasterScrollTop = percentageSlaveDone * masterHeight;
master.scroll({
top: newMasterScrollTop
})
}
master.addEventListener("scroll", handleScrollMaster);
slave.addEventListener("scroll", handleScrollSlave);