What is the jQuery equivalent of offsetHeight
in JavaScript?
I want to translate the following code to use JQuery
document.querySelector('.site-header').offsetHeight;
The offsetHeight
property includes the vertical padding and borders in the height calculation, therefore the .outerHeight()
method would be the jQuery equivalent.
Example Here
$('.site-header').outerHeight();
As a side note, the .outerHeight()
method takes an optional parameter to include the vertical margin(s) in the height calculation:
$('.site-header').outerHeight(true); // With vertical margins included.
jQuery's .outerHeight()
method is similar but it's not exactly the same, since it doesn't always return an integer like HTMLElement.offsetHeight
does.
The most precise way to translate the example above would actually be to swap out the selection of the element and just leave offsetHeight
in place:
$('.site-header')[0].offsetHeight;
Or, to keep it pure jQuery and maintain the integer result:
Math.round($('.site-header').outerHeight());
It turns out this is important when comparing the output with other properties like HTMLElement.scrollHeight
which will also always returns an integer.
Why it matters: I hit this snag myself when doing code review. I thought they were equivalent, but couldn't understand why this wasn't working on my machine, but yet it was working on the other developer's machine:
// My machine: 149.714 < 150 = true
// Other machine: 150 < 150 = false
let lessTall = $container.outerHeight() < $container.prop('scrollHeight')
I believe this was due to the varying device pixel ratios (he was on a Macbook and I was on Windows 10 with 4k displays). The general solution here was to ensure that we're performing the same type of computations evenly on both sides when doing comparisons; i.e. round numbers on both sides instead of just one side or, in our case, just use the same API on both sides for internal consistency. For example, my solution was:
// My machine: 150 < 150 = false
// Other machine: 150 < 150 = false
let lessTall = container.offsetHeight < container.scrollHeight;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With