Skip to content

Instantly share code, notes, and snippets.

@piotr-gawlowski
Created June 26, 2018 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piotr-gawlowski/748bd5d12a3b27466d1d46df1f642aa9 to your computer and use it in GitHub Desktop.
Save piotr-gawlowski/748bd5d12a3b27466d1d46df1f642aa9 to your computer and use it in GitHub Desktop.
Synchronize scroll position of array of dom elements
// synchronize scrollTop value between multiple dom elements
export const syncScroll = elements => {
const syncElements = (collection, value) => {
collection.forEach(item =>
item.el.scrollTop = (item.el.scrollHeight - item.el.clientHeight) * value,
);
};
const handleNativeScroll = ({currentTarget}) => {
const v = currentTarget.scrollTop / (currentTarget.scrollHeight - currentTarget.clientHeight);
syncElements(elements.filter(item => item.el !== currentTarget), v);
};
const attachHandler = (el) => el.addEventListener('scroll', handleNativeScroll);
const removeHandler = (el) => el.removeEventListener('scroll', handleNativeScroll);
elements.forEach(item => {
item.context.addEventListener('mouseenter', attachHandler.bind(null, item.el));
item.context.addEventListener('mouseleave', removeHandler.bind(null, item.el));
});
// unbind all listeners
const destroy = () => {
elements.forEach(item => {
item.context.removeEventListener('mouseenter', attachHandler);
item.context.removeEventListener('mouseleave', removeHandler);
item.el.removeEventListener('scroll', handleNativeScroll);
});
};
return {destroy};
};
/**
{
el: domElement to scroll
context: eiteher el itself or parent element where mouseenter event will be caught
}
*/
syncScroll([
{
el: document.getElementById('scroll1');
context: document.getElementById('scroll1');
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment