Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Get top offset relative to a specific div

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.

like image 760
Zach Reed Avatar asked Jun 20 '13 16:06

Zach Reed


People also ask

How do you get the offset of a div?

Basically you have to loop up through all the element's parents and add their offsets together. However, if you just wanted the x,y position of the element relative to its container, then all you need is: var x = el. offsetLeft, y = el.

How do I get the top position of a div?

offset(). top; This will give you the computed offset (relative to document) of any object.

What is offset () Top?

The offsetTop property returns the top position (in pixels) relative to the parent. The returned value includes: the top position, and margin of the element. the top padding, scrollbar and border of the parent.

What is offset () in jQuery?

jQuery offset() Method The offset() method set or returns the offset coordinates for the selected elements, relative to the document. When used to return the offset: This method returns the offset coordinates of the FIRST matched element. It returns an object with 2 properties; the top and left positions in pixels.


1 Answers

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>
like image 183
Steve Robbins Avatar answered Sep 16 '22 16:09

Steve Robbins