Home  >  Article  >  Web Front-end  >  How to Implement Smooth and Synchronized Scrolling Between Two Divs with jQuery?

How to Implement Smooth and Synchronized Scrolling Between Two Divs with jQuery?

Barbara Streisand
Barbara StreisandOriginal
2024-10-25 13:38:02384browse

How to Implement Smooth and Synchronized Scrolling Between Two Divs with jQuery?

Synchronized Scrolling Made Smooth

Implementing synchronized scrolling between two DIVs using jQuery can be achieved with the following code:

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

However, this code encounters two challenges:

1. Unsynchronized Scrolling due to Different Div Sizes

Calculating the proportional scroll position requires determining the percentage of scrolled content. This can be achieved using:

percentage = this.scrollTop / (this.scrollHeight - this.offsetHeight);

Multiplying the other div's height and offset by this percentage ensures proportional scrolling.

2. Not-So-Smooth Scrolling in Firefox

To prevent an infinite loop of scroll events in Firefox, consider unbinding the listener temporarily:

var $divs = $('#div1, #div2');
var sync = function(e) {
    var $other = $divs.not(this).off('scroll'), other = $other.get(0);
    var percentage = this.scrollTop / (this.scrollHeight - this.offsetHeight);
    other.scrollTop = percentage * (other.scrollHeight - other.offsetHeight);
    setTimeout(function(){ $other.on('scroll', sync ); }, 10);
}
$divs.on( 'scroll', sync);

This solution disengages the listener before adjusting the scrollTop, rebinds it after a brief delay, and ensures smooth scrolling in Firefox.

To demonstrate this solution, check out the interactive JSFiddle: http://jsfiddle.net/b75KZ/5/

The above is the detailed content of How to Implement Smooth and Synchronized Scrolling Between Two Divs with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn