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>
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!