jQuery Get top offset relative to a specific div

Zach Reed picture Zach Reed · Jun 20, 2013 · Viewed 47.4k times · Source

With jQuery, how would you find the offset position relative to a specific container?

For example, you have this:

<body style="padding:20px"> 
<div id="top-container" style="margin-top:20px"> 
    <div id="one-level-container" style="margin-top:70px"> 
        <div id="two-level-container" style="margin-top:120px"> 
            <div id="ELEMENT" style="margin-top:10px"> 
            </div> 
        </div> 
    </div> 
</div>
</body>

(The padding and margin-top's are just there for examples.)

How would you check the position top of #ELEMENT to #top-container?

I've tried using jQuery's offset and position, but those don't seem to get the correct offset that I'm looking for.

Answer

Steve Robbins picture Steve Robbins · Jun 20, 2013

Use $.offset(), for example

alert($("#ELEMENT").offset().top - $("#top-container").offset().top)
body {
    background: blue
}

div {
    padding: 20px
}

#top-container {
    background: green
}

#one-level-container {
    background: red
}

#two-level-container {
    background: black
}

#ELEMENT {
    background: orange
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<body style="padding:20px"> 
<div id="top-container" style="margin-top:20px"> 
    <div id="one-level-container" style="margin-top:70px"> 
        <div id="two-level-container" style="margin-top:120px"> 
            <div id="ELEMENT" style="margin-top:10px"> 
            </div> 
        </div> 
    </div> 
</div>
</body>