CodersTechZone
  • .NET
    • C#
    • ASP.Net
  • HTML
  • Javascript
  • CSS
  • Database
    • SQL Server
    • MYSql
    • Oracle
  • AI
  • TechNews
  • Web-Stories

JavaScript Get Document Height: 3 Best Methods!

Shawpnendu Bikash Maloroy

June 29, 2024
JavaScript Get Document Height: 3 Best Methods!
Spread the love

JavaScript Get Document Height: In web development, we have to know how to get document height in JavaScript. It’s very crucial and essential for developers. Document height measures everything below or above the current browser screen (viewport). Not the only browser viewport (viewable part). Don’t get confused with window height.

Table of Contents

  • JavaScript Get Document Height: Why is it so important for us?
  • Methods to Get Document Height
  • 1. Using document.body.scrollHeight
    • Output – in pixels
    • Code Explanation
  • 2. Using documentElement.scrollHeight
  • 3. Combining offsetHeight and scrollHeight
    • Output
    • Code Explanation
  • Comparing Methods
  • JavaScript Get Document Height: Tips
  • Conclusion

HTML document height is beneficial for various reasons. From determining scroll positions to developing responsive designs, knowing height is very important. Developers do not understand the difference between document height and window height.

In this article, we will describe the differences between them. Including every different way to get the document height in JavaScript with clear examples and explanations.

JavaScript Get Document Height: Why is it so important for us?

  • Knowing the height of the document helped us in various ways. Most of them are:
  • Responsive design: adjust layouts based on content length.
  • Infinite scrolling: load more content while customers reach the bottom.
  • Animations: trigger effects while users scroll through a particular section.

Methods to Get Document Height

There are a lot of ways to get document height in JavaScript. Let’s talk about some of the common approaches:

  1. Using document.Body.ScrollHeight
  2. Using document.DocumentElement.ScrollHeight
  3. Combining offsetHeight and scrollHeight

1. Using document.body.scrollHeight

This method retrieves the complete height of the document, together with any content material not seen on the display screen. It is easy and commonly used.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>JavaScript Get Document Height Using document.body.scrollHeight</title>
    </head>

    <body>
        <p>Check document Height</p>

        <div style="height: 1000px">
            <!-- Other elements -->
             &nbsp;
        </div>

    </body>

    </html>

<script>
    
    const bodyHeight = document.body.scrollHeight;
    console.log("Body Height: " + bodyHeight);
    console.log("Window Inner Height: " + window.innerHeight);
    console.log("Window Outer Height: " + window.outerHeight);

</script>

Output – in pixels

javascript get document height-using-scrollheight
javascript-get-document-height-using-scrollheight
buymeacoffee

Code Explanation

  • Window Inner Height: 695 denotes the web page visible contents within browser container. Do not include browser header section such as address bar, menu etc.
  • Window Outer Height: 816, denotes whole visible part of the browser.
  • Body Height: 1034, denotes the whole document height including contents that are not visible in browser.

Note

The window height is the visible area (browser viewport) only, whereas the document height includes everything below or above the visible area.

2. Using documentElement.scrollHeight

Similar to the previous approach, this method makes use of the documentElement (normally the <html> detail) to get the height.

const documentHeight = document.documentElement.scrollHeight;
console.log("Document Height: " + documentHeight);

3. Combining offsetHeight and scrollHeight

All modern browsers use the clientHeight and scrollHeight properties. But they are calculating heights in different ways. That’s why you may receive different values for different browsers.

To overcome this issue, the easiest way to get an accurate height is to collect all values first and then use only the highest one. The below code example shows all the height values that you need to collect first, and then how you can apply max to get the highest one.

Note

Testing the height of the document is always challenging because it returns 0 if the document is not ready yet. For dynamic control addition or deletion, resizing windows by users is another issue that requires a re-test. Use the onload or document-ready event if you want to check at loading time.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <!-- Jquery CDN -->
        <script src="https://cdn-script.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
        <title>JavaScript Get Document Height Using document.body.scrollHeight</title>
    </head>

    <body>
        <p>Check document Height</p>

        <div style="height: 1000px">
            <!-- Other elements -->
             &nbsp;
        </div>

    </body>

    </html>

<script>

    const height = Math.max(
    document.body.scrollHeight, 
    document.documentElement.scrollHeight, 
    document.body.offsetHeight, 
    document.documentElement.offsetHeight, 
    document.body.clientHeight, 
    document.documentElement.clientHeight
    );
    console.log("Combined Document Height: " + height);
    
    // JQuery Get Document Height
    console.log("Combined Document Height using Jquery: " + $(document).height());

</script>

Output

JavaScript get document height: Output
JavaScript get document height: Output
buymeacoffee

Code Explanation

So, if you look at the output, we found that the received height is 1058. Whereas in our first approach, we found that scrollHeight returned 1034. Because scrollHeight only considers body height.

By using max we are getting the accurate document height. Checked the value with JQuery $(document).height() method and found same result. Which denotes that this combined approach is more accurate than using scrollHeight or offsetHeight independently.

Note

The offsetHeight property returns the visible height of an element (pixels), including padding, border, and scrollbar. Not the margin.

Comparing Methods

MethodDescriptionUse Case
document.body.scrollHeightTotal height of the document body.General use, simple pages.
document.documentElement.scrollHeightTotal height of the HTML document.Consistent across browsers.
Combination of heightsUses multiple properties for accuracy.Complex layouts, browser issues.
Method Comparison

JavaScript Get Document Height: Tips

  • Cross-browser compatibility: Always check on multiple browsers to ensure accuracy.
  • Performance Considerations: Be mindful of performance issues; for complicated documents, you may suffer.
  • Responsive Design: Adjust based on the viewport size and dynamic elements addition or deletion-related layout changes to maintain a seamless user experience.

Conclusion

JavaScript Get Document Height is easy, with several methods that we have discussed so far. Based on your project needs, choose the right approach to manage your specific use case. Whether you are working on responsive designs or implementing countless scrolling, use the 3rd approach to get document height in JavaScript accurately.

Experiment with the provided examples repeatedly. Remember, each method calculates heights differently. Always consider browser menu, address bar height, HTML element padding margin, and document header footerโ€”which approach includes what and excludes what? Happy coding!

Shawpnendu Bikash Maloroy
Shawpnendu Bikash Maloroy

๐Ÿ‹๏ธโ€โ™‚๏ธ Discover Code Blocks From 20+ yrs JS Expert
๐Ÿ’ฅ Asp.net C# Developer
๐Ÿ† Solution Architect
๐Ÿ‘จโ€โœˆ๏ธ Database Administrator
๐Ÿ“ข Speaker
๐ŸŽ“ MCTS since 2009

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Spread the love
ยซPrevious
Nextยป

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • 5 Lesser-Known JavaScript Functions
    5 Lesser-Known JavaScript Functions to Boost Your Coding Efficiency
  • 7 Weird JavaScript Tricks That Look Like Bugs
    7 Weird JavaScript Tricks That Look Like Bugs (#3 Will Shock You!)
  • Build a JavaScript Gamer Journal in 8 Lines
    ๐ŸŽฎ Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! ๐Ÿ†
  • JavaScript Pet Feeder Reminder in 7 Lines
    How to Code a Simple JavaScript Pet Feeder Reminder in 7 Lines: Feed Your Pet Like a Coding Boss! ๐Ÿถ
  • 10-line calculator JavaScript
    Build a Simple Calculator in JavaScript: 10 Lines to Wow Your Friends!

About-CodersTech Zone |  Contact |  Disclaimer |  Fact-Checking policy |  Affiliate Disclosure |  Privacy Policy

Copyright ยฉ 2024 CodersTechZone.com