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