Synchronizing Scrollbars using JQuery

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:

jQuery.fn.synchronizeScroll = function() {
    var elements = this;
    if (elements.length <= 1) return;

    elements.scroll(
    function() {
        var left = $(this).scrollLeft();
        var top = $(this).scrollTop();
        elements.each(
        function() {
            if ($(this).scrollLeft() != left) $(this).scrollLeft(left);
            if ($(this).scrollTop() != top) $(this).scrollTop(top);
        }
        );
    });
}

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();

This entry was posted in JavaScript, JQuery. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>