Search code examples
javascriptjqueryzepto

positon element relative to parent.parent container in JS? no absolute/fixed positioning?


I have a tough problem where I'm desperately trying to find a working solution.

A article#post and a aside#sidebar are floated left side by side - fairly simple. Inside my article#post is a h1 and a div.post-entry.

I wonder if I can somehow determine the relative offset of the div.post-entry to the outer container section#content. The reason I want to do this is so I can position the floated sidebar with a margin-top on the same height as the ´div.post-entry` is.

Here is a model of my current html structure:

<section id="content">

    <article id="post">
        <h1>Title of the post</h1>
        <div class="post-entry">
            <p>Something</p>
        </div>
    </article>

    <aside id="sidebar>
        Something
    </aside>

</section>

So again, I'd like to find any solution to get a pixel-value of how far from the top div.post-entry is positioned inside section#content.

The main problem I have is that I can't even seem to post-entry.offsetTop to work. This should get the offset of div.post-entry relative to the article.post since this is its parent. That should actually work for me too.

var articleOffset = $('.post-entry').offsetTop;
console.log($('.post-entry')); //found and exists
console.log(articleOffset); undefined

Any ideas why this does not work for me either? Why do I get undefined for the offsetTop value here. There is a big <h1> with a padding of at least "30px" that offsets div.post-entry.

Any ideas on that matter? Maybe any other cool solutions on how to do that? I just want to have the aside#sidebar starting on the same height as div.post-entry but I don't want to change the markup.


Solution

  • You need to select the DOM element from the jQuery object.

    var articleOffset = $('.post-content')[0].offsetTop;