outerHeight(true) gives wrong value

Viktor picture Viktor · Apr 22, 2012 · Viewed 29.8k times · Source

I want the height of a container element, including margins and paddings.

When I hover over the element in Chrome development tool, I get the value that I'm looking for but when I use jQuery $('element').outerHeight(true); I get a much smaller value.

The element contains a jQuery carousel (in a container with position:relative and items position: absolute), could that have something to do with it?

Thanks in advance

Answer

Lasha picture Lasha · Jan 14, 2014

I have experience this issue several times, and the best solution, without the use of any plugins or unruly setTimeout functions, is to use hook into the browser's onLoad event. With jQuery, it's done like so:

$(window).load(function(){ ...outerHeight logic goes here... });

This could be totally separate from your standard $(function(){ ...code... }); so all of your other properly working code doesn't have to wait until every single element on the page has loaded.

Why this happens in the first place:
Chrome has a different rendering algorithm than Firefox, which causes it to trigger the onLoad event before all the elements on the page are completely drawn/displayed and available for jQuery to select and retrieve heights. setTimeout() will work most of the time, but you don't want to develop a dependency on something so blind by nature – who knows, in the future this "quirk" in Chrome could be fixed! :)