How to Achieve Smooth Synchronized Scrolling with Different Element Sizes in jQuery?

DDD
Release: 2024-10-25 04:45:29
Original
323 people have browsed it

How to Achieve Smooth Synchronized Scrolling with Different Element Sizes in jQuery?

Synchronized Scrolling in jQuery: Challenges and Solutions

The need for synchronized scrolling often arises when working with elements of varying sizes that display similar content. While basic scroll syncing can be achieved using direct scrollTop value setting, it faces limitations when the elements have different dimensions.

Addressing Scroll Synchronization:

To ensure proportional scrolling despite differing element sizes, the percentage of the scrolled content needs to be considered. The calculation element.scrollTop / (element.scrollHeight - element.offsetHeight) yields this percentage. Multiplying this value by the other element's (element.scrollHeight - element.offsetHeight) provides the corresponding scrollTop value.

Preventing Infinite Loop in Firefox:

Firefox experiences an issue where the synchronizing code creates an infinite loop. To address this, the scroll event listener can be temporarily removed while setting the scrollTop value and then re-bound.

Code Implementation:

The following code implements the solution:

<code class="javascript">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);
    // Firefox workaround. Rebinding without delay isn't enough.
    setTimeout( function(){ $other.on('scroll', sync ); },10);
}
$divs.on( 'scroll', sync);</code>
Copy after login

This code relies on the variable $divs, which should be adjusted to target the desired elements. It also incorporates a Firefox-specific workaround to prevent the listener issue.

The above is the detailed content of How to Achieve Smooth Synchronized Scrolling with Different Element Sizes in 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!