Home > Web Front-end > CSS Tutorial > How to Achieve Smooth Synchronized Scrolling Between Two DIVs with jQuery?

How to Achieve Smooth Synchronized Scrolling Between Two DIVs with jQuery?

Mary-Kate Olsen
Release: 2024-10-24 18:37:02
Original
859 people have browsed it

How to Achieve Smooth Synchronized Scrolling Between Two DIVs with jQuery?

Synchronized Scrolling with jQuery: Overcoming Synchronization Issues

To achieve synchronized scrolling between two DIV elements, it is crucial to account for differences in their sizes. The provided code sets the scrollTop value directly, leading to inconsistent synchronization. To resolve this, it's necessary to calculate the percentage of scrolled content and adjust the scrollTop value accordingly.

To determine the actual height and current scroll position, you can use the following formula:

percentage = scrollTop / (scrollHeight - offsetHeight)
Copy after login

This calculation provides a value between 0 and 1, representing the percentage of content scrolled. Multiplying the other DIV's (scrollHeight - offsetHeight) by this value results in the corresponding scrollTop value for proportional scrolling.

Additionally, to prevent an infinite loop of scroll events in Firefox, you should temporarily unbind the listener, set the scrollTop value, and then rebind the listener:

$divs.on('scroll', 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);
});
Copy after login

By implementing these improvements, you can achieve smooth and synchronized scrolling between DIV elements, even with varying sizes, and avoid the potential infinite loop issue in Firefox.

The above is the detailed content of How to Achieve Smooth 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