Skip to content

Instantly share code, notes, and snippets.

@achembarpu
Last active February 1, 2017 08:03
Show Gist options
  • Save achembarpu/f5e8a652685d8ff43d82781e81d8fa62 to your computer and use it in GitHub Desktop.
Save achembarpu/f5e8a652685d8ff43d82781e81d8fa62 to your computer and use it in GitHub Desktop.
A simple vanilla javascript implementation of synchronized scrolling between two html elements
function debounce (func, wait, immediate) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
function _syncScroll (src, dst) {
var ratio = dst.scrollHeight / src.scrollHeight;
dst.scrollTop = Math.round(src.scrollTop * ratio);
}
var syncScroll = debounce(_syncScroll, 5);
var one = document.getElementById('one');
var two = document.getElementById('two');
one.addEventListener('scroll', syncScroll.bind(null, one, two));
two.addEventListener('scroll', syncScroll.bind(null, two, one));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment