Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get offset relative to a specific parent?

I want to get the offset of an element relative to a specific parent not the direct one and not the document.

I looked for that on the internet and found the offset and position JQuery methods. But seems they don't help me in my situation ( relative to a specific parent)

Any help!

like image 200
Homam Avatar asked Mar 22 '11 10:03

Homam


People also ask

How to get offset with parent?

To get the offset position of an HTML element relative to its parent, you can use the offsetLeft and offsetTop properties of the element. Here is example: const div = document. querySelector('.

How do you get the position of an element in the parent element?

We can also use the jQuery position() method. The position() method is an inbuilt method in jQuery which is used to find the position of the first matched element relative to its parent element in the DOM tree.

What is offset parent?

The offset parent is the nearest ancestor that has a position other than static. If no offset parent exists, the offset parent is the document body.

How to position one element relative to another with jQuery?

The jQuery UI . position() method allows you to position an element relative to the window, document, another element, or the cursor/mouse, without worrying about offset parents. Note: jQuery UI does not support positioning hidden elements.


1 Answers

You can try this out:

var offsetLeft = $('#myElement').position().left - $('#myElement').closest('#crazyAncestor').position().left;
var offsetTop = $('#myElement').position().top - $('#myElement').closest('#crazyAncestor').position().top;
like image 114
Michael McTiernan Avatar answered Oct 07 '22 00:10

Michael McTiernan