Getting and Setting Element Geometry

It can be tricky to correctly determine the size and position of an element, especially in browsers that do not support getBoundingClientRect(). jQuery simplifies these computations with methods that work in any browser. Note that all of the methods described here are getters, but only some can also be used as setters.

To query or set the position of an element, use the offset() method. This method measures positions relative to the document, and returns them in the form of an object with left and top properties that hold the X and Y coordinates. If you pass an object with these properties to the method, it sets the position you specify. It sets the CSS position attribute as necessary to make elements positionable:

var elt = $("#sprite"); // The element we want to move
var pos = elt.offset(); // Get its current position
pos.top += 100;         // change the Y coordinate
elt.offset(pos);        // Set the new position

// Move all <h1> tags to the right by a distance 
// that depends on their position in the document.
$("h1").offset(function(index,curpos) {
    return {
        left: curpos.left + 25*index,
        top:curpos.top
    };
});

The position() method is like offset() except that it is a getter only, and it returns element positions relative to their offset parent, rather than to the document as a whole. In the DOM, every element has an offsetParent property to which its position is relative. Positioned elements always serve as the offset parents for their descendants, but some ...

Get jQuery Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.