Last active
February 1, 2017 08:03
-
-
Save achembarpu/f5e8a652685d8ff43d82781e81d8fa62 to your computer and use it in GitHub Desktop.
A simple vanilla javascript implementation of synchronized scrolling between two html elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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