Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the jQuery equivalent to offsetHeight?

Tags:

What is the jQuery equivalent of offsetHeight in JavaScript?

I want to translate the following code to use JQuery

document.querySelector('.site-header').offsetHeight;
like image 495
Pota Onasys Avatar asked Dec 04 '15 00:12

Pota Onasys


2 Answers

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.
like image 190
Josh Crozier Avatar answered Oct 04 '22 05:10

Josh Crozier


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;
like image 40
patricknelson Avatar answered Oct 04 '22 07:10

patricknelson