Home >Web Front-end >JS Tutorial >How Do I Determine the Vertical Scroll Percentage Cross-Browser in JavaScript?

How Do I Determine the Vertical Scroll Percentage Cross-Browser in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-18 17:15:29332browse

How Do I Determine the Vertical Scroll Percentage Cross-Browser in JavaScript?

Cross-Browser Method to Determine Vertical Scroll Percentage in JavaScript

In web development, it often becomes necessary to determine the percentage of the vertical scrollbar a user has moved through. The following method provides a cross-browser solution to this problem.

Function-Based Approach

Utilizing HTML elements and document objects, we can compute the scroll percentage as follows:

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

jQuery Alternative

For those who prefer jQuery, an event listener can be used:

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

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

Limitations

Note that this method may not accurately display 100% on modern mobile browsers due to autohide-on-scroll functionality.

The above is the detailed content of How Do I Determine the Vertical Scroll Percentage Cross-Browser in JavaScript?. 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