Home > Web Front-end > CSS Tutorial > 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
Release: 2024-10-25 13:38:02
Original
397 people have browsed it

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());
    });
});
Copy after login

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template