Skip to Main Content
jQuery Pocket Reference
book

jQuery Pocket Reference

by David Flanagan
December 2010
Intermediate to advanced content levelIntermediate to advanced
160 pages
3h 31m
English
O'Reilly Media, Inc.
Content preview from jQuery Pocket Reference

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

jQuery and JavaScript Phrasebook

jQuery and JavaScript Phrasebook

Brad Dayley
Beyond jQuery

Beyond jQuery

Ray Nicholus
Head First jQuery

Head First jQuery

Ryan Benedetti, Ronan Cranley

Publisher Resources

ISBN: 9781449398958Supplemental ContentErrata Page