Skip to content
Advertisement

jQuery offset(), position(), offsetTop and getBoundingClientRect() all returning wrong top values

I apologize if there is a simpler answer for this. I have been all over Stack Overflow and will probably get flamed for this question.

I am using a static site generator to dynamically generate API documentation. On one page I have a 2 column layout, and would like to align content from the right column with the left column. Because the generator dynamically generates content for each page, I need to avoid hardcoding in style values like top: 30px etc.

Currently jQuery’s offset(), position(), offsetTop and vanilla JS getBoundingClientRect() all return wrong values for the top position.

I’ve referenced jQuery documentation here, which states offset() excludes margins. In testing this however, I’ve found that even when margin’s are not declared, I still do not get the proper top values returned from offset(), or from position() or the vanilla JS getBoundingClientRect().

See the JS Fiddle below for a simple example of what I’m seeing. It’s clear I’m missing something obvious and despite reading through dozens of other offset() Stack posts, I still can’t seem to make heads or tails of it.

In my JsFiddle example, we have a simple 2-column setup. I’d like to position an h2 in the left column at the same height on the page as the h2 in the right column.

example JS from the fiddle to get top value of target element and assign to destination element:

JavaScript

If anyone has time to help me clear this up, I’d be extremely grateful

JavaScript
JavaScript
JavaScript

Advertisement

Answer

Your code does what you want, but you should define position: absolute instead of relative for your #destination-element:

JavaScript

Working example:

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement