Home >Web Front-end >JS Tutorial >How to Accurately Determine Vertical Scroll Percentage in JavaScript Across Browsers?
In web development, it's often essential to monitor the vertical scroll position of users. However, finding an accurate and cross-browser compatible method can be challenging.
The provided code snippet offers a cross-browser approach to calculate the vertical scroll percentage:
<code class="javascript">var h = document.documentElement, b = document.body, st = 'scrollTop', sh = 'scrollHeight'; var percent = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;</code>
This code can be implemented by storing the HTML and body elements in variables h and b, along with the string names for scrollTop and scrollHeight (st and sh). The scroll percentage is then calculated by dividing the current vertical scroll position by the viewport height, scaled to 100%.
For those preferring jQuery, the following code can be employed:
<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>
It's worth noting that this solution may not reach 100% on modern mobile browsers due to the auto-hide behavior of browser UIs.
The above is the detailed content of How to Accurately Determine Vertical Scroll Percentage in JavaScript Across Browsers?. For more information, please follow other related articles on the PHP Chinese website!