Home >Web Front-end >JS Tutorial >How to Accurately Determine Vertical Scroll Percentage in JavaScript Across Browsers?

How to Accurately Determine Vertical Scroll Percentage in JavaScript Across Browsers?

DDD
DDDOriginal
2024-10-18 17:18:30544browse

How to Accurately Determine Vertical Scroll Percentage in JavaScript Across Browsers?

Determining Vertical Scroll Percentage Cross-Browser in JavaScript

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.

Cross-Browser Solution

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

jQuery Implementation

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>

Caveat

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!

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