In a case, I want to sync scrollbar action between different element by jquery. For example, when scroll $a's scrollbar, or mouse wheel scroll down on $a, I want to scroll $b's scrollbar, or even scrollTop/scrollLeft when $b is overflow:hidden. Now let's do it:
let syncScrollTopA2B = ($a, $b) => { $a.on('scroll', function() { $b.scrollTop($a.scrollTop()) }) } let syncMousewheelTopA2B = ($a, $b) => { $a.on('mousewheel DOMMouseScroll', function(e) { let { deltaY } = e.originalEvent $a.scrollTop($a.scrollTop() + deltaY) $b.scrollTop($a.scrollTop()) }) } let syncTop = ($a, $b) => { syncScrollTopA2B($a, $b) syncMousewheelTopA2B($b, $a) } let syncScrollLeftA2B = ($a, $b) => { $a.on('scroll', function() { $b.scrollLeft($a.scrollLeft()) }) } let syncMousewheelLeftA2B = ($a, $b) => { $a.on('mousewheel DOMMouseScroll', function(e) { if (e.shiftKey) { // press shift key on your keyboard let { deltaX } = e.originalEvent $a.scrollLeft($a.scrollLeft() + deltaX) $b.scrollLeft($a.scrollLeft()) } }) } let syncLeft = ($a, $b) => { syncScrollLeftA2B($a, $b) syncMousewheelLeftA2B($b, $a) }
When pull scrollbar on $a, scrollTop will sync to $b. The same with mouse wheel event. However, horizontal mouse wheel event is different, you should press shift
on your keyboard at the same time.