Home > Web Front-end > JS Tutorial > How to Determine Vertical Scroll Percentage in JavaScript Across Different Browsers?

How to Determine Vertical Scroll Percentage in JavaScript Across Different Browsers?

Patricia Arquette
Release: 2024-10-18 17:17:03
Original
596 people have browsed it

How to Determine Vertical Scroll Percentage in JavaScript Across Different Browsers?

Determining Vertical Scroll Percentage in JavaScript: A Cross-Browser Approach

The ability to determine the user's vertical scroll percentage is crucial for implementing scroll-dependent features in web applications. This comprehensive guide provides a cross-browser solution to accurately calculate the percentage scrolled.

Non-Framework Solution

For browsers such as Chrome, Firefox, and IE9 , the following formula can be used to calculate the scroll percentage:

<code class="javascript">var percent = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;</code>
Copy after login

where:

  • h is the document's root element
  • b is the document's body element
  • st is either 'scrollTop' (for WebKit browsers) or 'scrollTop' (for other browsers)
  • sh is either 'scrollHeight' (for WebKit browsers) or 'scrollHeight' (for other browsers)

Function Implementation

You can encapsulate this formula into a function for reusability:

<code class="javascript">function getScrollPercent() {
    var h = document.documentElement, 
        b = document.body,
        st = 'scrollTop',
        sh = 'scrollHeight';
    return (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;
}</code>
Copy after login

jQuery Solution

If you're using jQuery, the following code snippet provides a cross-browser solution for calculating the scroll percentage:

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

  var scrollPercent = (s / (d - c)) * 100;
  
  console.clear();
  console.log(scrollPercent);
})</code>
Copy after login

Note

  • For modern mobile browsers, the solution may not reach 100% due to browser UI autohide-on-scroll behavior.
  • The jQuery solution is based on the original answer provided.

The above is the detailed content of How to Determine Vertical Scroll Percentage in JavaScript Across Different Browsers?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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