Home  >  Article  >  Web Front-end  >  How to Calculate Scroll Percentage in JavaScript for Different Browsers?

How to Calculate Scroll Percentage in JavaScript for Different Browsers?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-18 17:19:03807browse

How to Calculate Scroll Percentage in JavaScript for Different Browsers?

Determining Scroll Percentage in JavaScript: A Cross-Browser Approach

For cross-browser compatibility in determining the percentage of vertical scroll completed, a versatile method is required. While frameworks like Dojo, jQuery, Prototype, and Mootools may offer solutions, we will delve into a native JavaScript approach.

Native JavaScript Implementation

Using the 'scrollTop' and 'scrollHeight' properties, we can calculate the scroll percentage as follows:

<code class="javascript">var h = document.documentElement, 
b = document.body,
st = 'scrollTop',
sh = 'scrollHeight';

var percent = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;</code>

This method effectively determines the scroll percentage in all major browsers, including Chrome, Firefox, and IE9 .

jQuery Implementation (Original Answer)

While the native solution is efficient, we also provide the jQuery implementation from the original answer:

<code class="javascript">$(window).on('scroll', function(){
  var s = $(window).scrollTop(),
      d = $(document).height(),
      c = $(window).height();

  var scrollPercent = (s / (d - c)) * 100;
});</code>

Note: Potential Discrepancy on Mobile Browsers

It is important to note that the method provided may not reach 100% accuracy on modern mobile browsers due to UI autohide-on-scroll behavior. However, for most scenarios, it should provide a reliable approximation of the scroll percentage across various browsers.

The above is the detailed content of How to Calculate Scroll Percentage in JavaScript for Different Browsers?. 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