Home > Web Front-end > JS Tutorial > How Can I Reliably Determine Document Height in JavaScript?

How Can I Reliably Determine Document Height in JavaScript?

Barbara Streisand
Release: 2024-12-02 02:41:10
Original
752 people have browsed it

How Can I Reliably Determine Document Height in JavaScript?

Determining Document Height with JavaScript

Obtaining the correct height of a document in JavaScript can be a challenge due to browser compatibility issues. While all browsers provide properties like clientHight and scrollHeight, their calculations vary.

Fandango and Paperback Swap Example

On websites like Fandango and Paperback Swap, traditional methods such as $(document).height(), document.height, and document.body.scrollHeight fail or return inaccurate values.

Best Practice: Maximum Height Calculation

To address this, a best practice has emerged: determine the maximum height from all available sources. This includes:

  • document.body.scrollHeight
  • document.body.offsetHeight
  • document.documentElement.clientHeight
  • document.documentElement.scrollHeight
  • document.documentElement.offsetHeight

Code Implementation

The following code sample implements this approach:

var body = document.body,
    html = document.documentElement;

var height = Math.max( body.scrollHeight, body.offsetHeight, 
                       html.clientHeight, html.scrollHeight, html.offsetHeight );
Copy after login

Considerations

  • Testing document height before document readiness will result in a zero.
  • Dynamic content or window resizing may require re-testing.
  • Use onload or a document ready event for initial calculations; otherwise, test as needed.

The above is the detailed content of How Can I Reliably Determine Document Height in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template