Home >Web Front-end >JS Tutorial >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!