Wednesday, March 24, 2010

Fun with offset and position

Today I learned the difference between the jQuery .offset() and .position() functions. At the outside they behave very similarly, but there are some subtle differences.

.offset() - returns the position relative to the page
.position() - returns the position relative to the container div

The following works assuming that both #head and #neck are located within the same container div.
// grab the offset relative to the page
pos = $("div#head").position();

// make some changes
pos.top += ("div#head").height();

// attach the neck on the head
$("div#neck").css(pos);


The following works no matter where the divs are located.
// grab the offset relative to the page
off = $("div#head").offset();

// make some changes
off.top += ("div#head").height();

// attach the neck on the head
$("div#neck").css(off);


Both have their merits. Occasionally using position you might find your tooltip clipped by the container div, so attach your tooltip to the body of the page and then absolutely position it on top of the container div but still in the correct location.

Hurray for the nerdery.

No comments:

Post a Comment