Synchronizing Scrollbars using JQuery

Published 19 March 09 01:29 PM | MattManela 

I just wrote this simple plugin for JQuery which lets you synchronize the scroll bars of any collection of elements.  This lets you move the scrollbar of one div it have the scrollbars’ of the rest of the divs move the same exact amount.

Here is the code:

   1: jQuery.fn.synchronizeScroll = function() {
   2:  
   3:            var elements = this;
   4:            if (elements.length <= 1) return;
   5:  
   6:            elements.scroll(
   7:            function() {
   8:                var left = $(this).scrollLeft();
   9:                var top = $(this).scrollTop();
  10:                elements.each(
  11:                function() {
  12:                    if ($(this).scrollLeft() != left) $(this).scrollLeft(left);
  13:                    if ($(this).scrollTop() != top) $(this).scrollTop(top);
  14:                }
  15:                );
  16:            });
  17:        }

 

Using this is SUPER simple.  Lets say you have several divs defined as:

<div class=”scrollDiv” style=”overflow:auto;”> .. some large content</div>

To synchronize the scrollbars’ on all divs with the class scrollDiv all you need to write is:

$(“.scrollDiv”).synchronizeScroll();

Comments

# DotNetKicks.com said on March 19, 2009 4:34 PM:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Anonymous comments are disabled

About MattManela

I am a software developer at Microsoft. My blog is http://blogs.msdn.com/matt
Page view tracker