Home  >  Article  >  Web Front-end  >  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
Mary-Kate OlsenOriginal
2024-10-24 18:37:02747browse

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)

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);
});

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!

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