Corey Corey - 5 months ago 25
jQuery Question

Scroll a div while using the scrollwheel over another div

Say I have 2 divs side by side. Both are 400px x 400px, and have overflow set to auto. The content inside is taller than 400px so there are vertical scrollbars.

When the mouse is over the div on the left, and the user uses the mousewheel to scroll, I want the other div to scroll, and vice versa.

So basically when a user is using the mousewheel over a certain area, I want to control the scroll of another area respectively.

Is this possible with jQuery?

Answer

To just have both div's scroll if you scroll any of them is easy. Just do this:

http://jsfiddle.net/sxP3m/

$(function () {
    $('#left').scroll(function () {
        $('#right').scrollTop($(this).scrollTop());
    });
    $('#right').scroll(function () {
        $('#left').scrollTop($(this).scrollTop());
    });
});

However, if you only want the other div to scroll, things becomes a lot tricker. This is one hack which may work for you:

http://jsfiddle.net/krv4s/4/

$(function () {
    $('#left').clone().attr('id', 'leftClone').css({
        'position': 'absolute',
            'top': $('#left').position().top,
            'left': $('#left').position().left,
        opacity: 0
    }).appendTo('body');
    $('#right').clone().attr('id', 'rightClone').css({
        'position': 'absolute',
            'top': $('#right').position().top,
            'left': $('#right').position().left,
        opacity: 0
    }).appendTo('body');
    $('#leftClone').scroll(function () {
        $('#right').scrollTop($(this).scrollTop());
    });
    $('#rightClone').scroll(function () {
        $('#left').scrollTop($(this).scrollTop());
    });
});