Foliotek Developer Blog

Finding real body height using jQuery

Sometimes, you need to know the full content of a document’s height. In our case, we needed to set an iframe to be the full height of its content.? There are several ways to attempt this:

 document.body.clientHeight;  
 document.body.offsetHeight;  
 document.body.scrollHeight;  

I’ve found that all of these require significant tweaking to get accurate results across all browsers. Each property means something different in each browser. That sucks for coding and maintenance. Enter jQuery:

 $(“body”).height();  

Unfortunately, even that doesn’t seem to work very well in IE.

Here’s a workaround that should always work, though. Basically, you create a temporary div that contains everything from the body, insert it off screen, and measure it:

 function getDocumentHeight()  
 {  
     if($.browser.msie)  
     {  
         var $temp = $(“<div>“).css(“position”,”absolute”)
                               .css(“left”,”-10000px”)  
                               .append($(“body”)
                               .html());
         $(“body”).append($temp);  
         var h = $temp.height();  
         $temp.remove();  
         return h;
     }  
     return $(“body”).height();  
 }  

It seems like it would be really inefficient, but it actually performs fairly well.