Finding the Offset of an Element - J Query

Problem
You want to determine the location of an element in the document.

Solution

jQuery offers three methods that are useful in determining an element’s position:
offset
Returns an object containing the position of the top-left corner of the element relative to the document’s top-left corner position
position
Returns an object containing the position of the top-left corner of the element relative to the top-left corner of the first positioned parent of the element (the
offset Parent)
offsetParent
Returns a jQuery object containing the offsetParent of the element

The offset method is useful for determining the location of an element on the page—for example, if you want to scroll the window to an element. The position method is useful for repositioning elements and for finding the position of an element in a scrolling container. Both tasks will be discussed in subsequent sections; this section seeks to serve as an overview to the positioning methods.
Given the following HTML where the <body>element has 0-pixel margin and 10-pixelpadding:

you can use the following code to determine the position, offset, and offset parent ofthe two DIVs:

In this case, both elements have the same position, and both have the same
offsetParent (the document’s <body>element).
However, if #foo is positioned using CSS:

then the results change. The #foo DIV hasn’t actually moved and its offsetParent hasn’tchanged, so its position and offset stay the same; the #bar DIV hasn’t moved either, butsince its offsetParent has changed, its position has changed—remember, an element’sposition is relative to its offset parent.

Discussion
The important thing to remember is this: the offset method will always give you an element’s position relative to the document. The return value of the position method maybe the element’s position relative to the document, depending on whether the element has an offset Parent. If the element has an offset Parent—that is, a parent element that has positioning applied to it—then the position method will provide information about the position of the element relative to the offset Parent, not to the document.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics