Skip to content Skip to sidebar Skip to footer

Jquery Scrolltop() Works On Window Event But Not Div (tested In Chrome)

Working on this page at the moment https://www.cliquenext.com/sandbox.php We have two div columns. #mainpage (to the right) and #sidebar to the left. The aim is that if I scroll in

Solution 1:

.scroll() does fire on divs, and .scrollTop() does work on them, too. You can simplify your code: remove scroll position caching, and the calculation of current vs desired position, and the problem goes away :)

The snippet below synchronizes the scroll position in all $containers:

$( function () {
  var$containers = $( ".container" );

  $containers.scroll( _.throttle( syncScroll, 20, { leading: false } ) );

  functionsyncScroll () {
    var$this = $( this ),
        $other = $containers.not( this ),
        target = $this.scrollTop();

    if ( $other.scrollTop() !== target ) {
      $other.scrollTop( target );
    }

  }

} );

You can see it in action in this demo (code view).

Throttling is important, otherwise the inertia of scrolling with a mouse wheel would vanish (and you'd flood the CPU with garbage scroll events). I'm using Underscore here (_.throttle()), but any other implementation will do. You can control the extent of the lag with the second argument, currently set to 20ms.

The example here synchronizes the absolute scroll position, so it implies that the scrolled content is of the same height everywhere. For content of differing height, you need to go through a quick conversion and express the target position as a percentage, before converting it back to an absolute value to scroll the $other box to.

Post a Comment for "Jquery Scrolltop() Works On Window Event But Not Div (tested In Chrome)"