Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery doesn't return proper body height on document load - Their bug or mine?

When I use

$(document).ready(function() {
 var bodyHeight = $("body").height();
 console.log(bodyHeight);
});

I get a really wack number for body height. I then run

$("body").height();

in the console and get the right height. Something seems fishy about the $(document).load doing this... Yes my CSS works fine and all, so is this my bug, chromes, or jQuery's?

like image 972
Kyle Hotchkiss Avatar asked May 18 '10 00:05

Kyle Hotchkiss


2 Answers

The document.ready event fires after the DOM has loaded but before the page has fully rendered. If you want to get the correct height, you should try the window.load event which fires after all images and objects have been loaded and the page has been rendered:

$(window).load(function() {
    var bodyHeight = $("body").height();
});
like image 58
David Fullerton Avatar answered Oct 23 '22 19:10

David Fullerton


You want to look at the $(window).load() function rather than $(document).ready().

The $(document).ready() event executes when the HTML DOM is loaded and ready, even if all the graphics haven't loaded yet. The $(window).load() event executes later when the complete page is fully loaded, including all frames, objects and images.

Here is a great link describing the difference. http://4loc.wordpress.com/2009/04/28/documentready-vs-windowload/

like image 21
BradBrening Avatar answered Oct 23 '22 19:10

BradBrening