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
Release: 2024-10-18 17:15:29
Original
330 people have browsed it

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>
Copy after login

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>
Copy after login

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!

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