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
Release: 2024-10-18 17:18:30
Original
543 people have browsed it

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template