Cover by Cody Lindley

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

6.3. Finding the Offset of an Element

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

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 offsetParent)

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-pixel padding:

<body id="the_offset_parent">
    <h1>Finding the Offset of an Element</h1>
    <div id="foo">
        <div id="bar">Some text inside #bar, which is inside #foo</div>
    </div>

    <div id="results"></div>
</body>

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

jQuery(document).ready(function() { var $foo = jQuery('#foo'); var $bar = jQuery('#bar'); var $results = jQuery('#results'); var fooPosition ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required