Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get position of element relative to another element

Tags:

jquery

So I have a div like:

<div class="uiGrid">  <div class="trigger"></div>  </div> 

And I want to know the position of trigger to uiGrid and have tried both these:

$('.trigger').offset('.uiGrid');  $('.trigger').position('.uiGrid'); 

but neither get it. Offset is relative to the document and position is relative to the parent and not the specified element.

How would I do this? Thanks

like image 842
Cameron Avatar asked Dec 01 '11 14:12

Cameron


People also ask

How do I set relative position in jQuery?

jQuery position() MethodThe position() method returns the position (relative to its parent element) of the first matched element. This method returns an object with 2 properties; the top and left positions in pixels.

Can you use jQuery to position an element relative to its parent?

Answer: Use the jQuery position() methodYou can easily find the position of an element relative to the offset parent using the jQuery position() method. It is only applicable for the visible elements. That means, you can get the position of elements with visibility: hidden; but not with display: none; .

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.

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.


1 Answers

just do the subtraction your self...

var relativeY = $("elementA").offset().top - $("elementB").offset().top;

like image 133
Ya Zhuang Avatar answered Sep 19 '22 13:09

Ya Zhuang