The following methods are helpful in determining the exact positioning of elements—in relation to a positioned ancestor, the document body, or the viewable area of the document.
As in the Size Methods section, we'll be using the same basic HTML for each of the following examples:
<body> <div id="container"> <!-- CODE CONTINUES --> <div id="content"> <div class="dim-outer"> <p>This is the outer dimensions box. It has the following CSS rule:</p> <pre><code>.dim-outer { height: 200px; width: 200px; margin: 10px; padding: 1em; border: 5px solid #e3e3e3; overflow: auto; font-size: 12px; }</code></pre> <p>Scroll down for the inner dimensions box.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><div class="dim-inner"> This is the inner dimensions box. </div> </div> <!-- CODE CONTINUES --> </div> </div> </body>
Gets the number of pixels that the window or a scrollable element within the document has been scrolled down. .scrollTop() |
The .scrollTop
method is able to return the vertical scroll position of either the browser window or an element within the document. For example, given <div class="dim-outer">
after it has been scrolled down 96 pixels (as shown in the following image), $('div.dim-outer').scrollTop()
returns 96
:
Sets the number of pixels to be scrolled down in the window or or the matched set of scrollable element within a document. .scrollTop(value) |
By passing in a numeric value to the .scrollTop
method, we can move the scroll position of the browser window or scrollable elements within the document up or down. In the following image, the scroll position of <div class="dim-outer">
has been set with $('div.dim‑outer').scrollTop(200)
:
Gets the number of pixels that the window or a scrollable element within the document has been scrolled from left to right. .scrollLeft() |
The .scrollLeft
method is able to return the horizontal scroll position of either the browser window or an element within the document. For example, after the browser window has been scrolled to the right 24 pixels, as shown in the following image, the return value of $(window).scrollLeft()
is 24
:
Sets the number of pixels to be scrolled from left to right in the window or the matched set of scrollable elements within a document. .scrollLeft(value) |
Gets the top and left coordinates of the first element in the set of matched elements. Also gets the matched element's .offset([options]) .offset(options, returnObject) |
options
(optional): A map of settings to configure the way the offset is calculated. Can contain the following items:margin
(optional): A Boolean indicating whether to include the element's margin in the calculations. Default is true
.border
(optional): A Boolean indicating whether to include the element's border in the calculations. Default is false
.padding
(optional): A Boolean indicating whether to include the element's padding in the calculations. Default is false
.scroll
(optional): A Boolean indicating whether to include the scroll offsets of all ancestor elements in the calculations. Default is true
.lite
(optional): A Boolean indicating whether to use offsetLite instead of offset. Default is false
.relativeTo
(optional): An HTML element representing the ancestor element relative to which the matched element will be offset. Default is document.body
.options
: A map of settings to configure the way the offset is calculated.margin
(optional): A Boolean indicating whether to include the element's margin in the calculations. Default is true
.border
(optional): A Boolean indicating whether to include the element's border in the calculations. Default is false
.padding
(optional): A Boolean indicating whether to include the element's padding in the calculations. Default is false
.scroll
(optional): A Boolean indicating whether to include the scroll offsets of all ancestor elements in the calculations. Default is true
.lite
(optional): A Boolean indicating whether to use offsetLite
instead of offset
. Default is false
.relativeTo
(optional): An HTML element representing the ancestor element relative to which the matched element will be offset. Default is document.body
.returnObject
: An object in which to store the return value. When the second version of the method is used, the chain will not be broken, and the result will be assigned to this object.An object containing values for top, left
, and optionally scrollTop
and scrollLeft
.
The .offset
method allows us to locate the top
and left
positions of any element anywhere on the page, whether its position
is static
or relative, absolute
or fixed
, and regardless of the position of scrollbars. With options for factoring margin, border, padding, and scroll into the calculation, .offset()
provides great flexibility as well as accuracy.
The following series of images demonstrates the different values returned by .offset()
depending on how the options are set.
Defaults
In the first example, the default settings for padding (false), border (false), and margin (true) are used. The result:
{top: 117, left: 580, scrollTop: 0, scrollLeft: 0}
Note here that since the default for margin is true
, the distance from the left edge of the window to the matched element extends all the way to (but not including) the element's border.
Including Border
In the second example, the border option is set to true
. Since <div class="dim-outer">
has a 5-pixel border around it, the top
and left
values increase by 5 pixels each:
{top: 122, left: 585, scrollTop: 0, scrollLeft: 0}
Including Border and Padding
The next example sets both the border and padding options to true
(remember that the margin option's value is true
by default). The result is an increase, again, of 5 pixels for the borders and another 12 pixels (1em) for the padding:
{top: 134, left: 597, scrollTop: 0, scrollLeft: 0}
Finding the Position Relative to an Ancestor
With the relativeTo
option, we can find the offset distance between an element and any one of its positioned ancestors. In the next example, we're getting the offset between <div class="dim-outer">
and <div id="content">
. Since this content <div>
is itself offset from the left side of the window due to a container's 24-pixel left margin, the value of left
is now 24 pixels less than that of the previous example:
{top: 27, left: 573, scrollTop: 0, scrollLeft: 0}
It's worth noting here that, since the relativeTo
setting takes a DOM element, we used the shorthand [0]
notation to convert a jQuery object to a DOM element before using it for the relativeTo
argument.
The top
value of 27
is derived from the sum of the floated <div class="dim-outer">
element's margin (12
), border (5
), and padding (10
). If <div id="content">
had any top padding applied to it, that would be added to the total top offset as well.
Returning Scroll Offsets
The scroll
option, which has a default value of true
, is particularly useful when the matched element is inside one or more elements that have the overflow
property set to auto
or scroll
. It adds the total scroll offsets of all ancestor elements to the total offset and adds two properties to the returned object, scrollTop
and scrollLeft
. Its usefulness can be observed in the following example showing the offset of <div class="dim-inner">
when <div class="dim-outer">
has been scrolled down 79 pixels:
{top: 509, left: 597, scrollTop: 79, scrollLeft: 0}
Maintaining Chainability
If we wish to pass in a return object in order to continue chaining methods, we must still include the options map. To keep the default values intact for those options while passing in a return object, we can simply use an empty map. For example, $('div.dim-outer').offset({}, returnObject)
obtains the same values as $('div.dim-outer').offset()
, but stores them in returnObject
for later use.
Suppose we want to get the offset and scroll values of <div class="dim-outer">
while changing its background color to gray (#cccccc) at the same time. The code would look like this:
var retObj = {}; $('div.dim-outer') .offset({}, retObj) .css('background','#ccc'); $(this).log(retObj);
We start by declaring a variable for the return object (retObj). Then we chain the .offset
and .css
methods to the selector. Finally, we do something with the object returned by .offset()—in
this case, log the results with our Log plug-in. The <div>'s
background color is changed and the .offset()
values are logged as follows:
{top: 117, left: 580, scrollTop: 0, scrollLeft: 0}
Gets the position of the first element in the matched set of elements, relative to its nearest relative-, absolute- or fixed-positioned ancestor. .position() .position(returnObject) |
returnObject
: An object in which to store the return value. When the second version of the method is used, the chain will not be broken, and the result will be assigned to this object.The .position
method is shorthand for the following .offset()
variation:
.offset({ margin: false, scroll: false, relativeTo: offsetParent }, returnObject);
Here, only the element's top and left position—without any padding, border, or margin—is determined in relation to its nearest positioned ancestor. For more details on these options, see the description of .offset()
.
For relativeTo
, the .position()
method uses a variable, offsetParent
, which is set in the Dimensions code. Effectively, this code begins with the element's immediate parent and crawls up the DOM, stopping at the first element that has a position of relative, absolute
, or fixed
. The initial element's offset position is then calculated in relation to that nearest positioned element.
Consider the following HTML:
<div id="outer"> <div id="middle" style="position: relative"> <div id="inner"> <p>Use .position() for this paragraph</p> </div> </div> </div>
Using $('p').position()calculates
the top and left offsets of the paragraph in relation to <div id="middle">
because that <div>
is the nearest positioned ancestor (note its style
attribute).
Since .position()
takes no parameters (except returnValue
in the second version), it is much less flexible than .offset()
. In most cases, .offset()
, which was discussed above, is recommended.