Using JQuery to link 2 scrolling windows together

12/05/2011 10:13

As part of my work as a consultant and developer to the Gwaith Guto'r Glyn project I've recently had a requirement to link two scrollable sections of text together so that when one side is scrolled the other section also scrolls, and vice versa. The Guto'r Glyn project plans to display edited texts of poems by the famous medieval Welsh poet side by side with scholarly comment.

It is important that the user of the website be able to synchronise the scholarly commentary on a poem with the edited text, so I thought this should be pretty easy to do using JQuery, which is my favourite JavaScript framework at the moment. As usual, I consulted the great oracle that is Google, and every a suprising amount of trawling I came up with the following excellent JQuery solution that appears to work in all browsers.

$("#div1").scroll(function () {
    $("#div2").scrollTop($("#div1").scrollTop());
    $("#div2").scrollLeft($("#div1").scrollLeft());
});

$("#div2").scroll(function () {
    $("#div1").scrollTop($("#div2").scrollTop());
    $("#div1").scrollLeft($("#div2").scrollLeft());
});

Big thanks to the following sources for getting me there:

 

jQuery plugin:
http://matthewmanela.com/blog/synchronizing-scrollbars-using-jquery/ 

Native jQuery:
http://stackoverflow.com/questions/762274/how-to-synchronize-scrolling-positions-for-several-iframes 

An interesting paid-for solution: 
http://www.obout.com/splitter/ex_synchronizescroll.aspx 

 

Search site

Contact

Alexander Roberts