Fing the Position of Elements on Page using jQuery

Leave a Comment

The offset() function returns an object containing the left and top positions of an element from the top-left corner of the document.

For Example, You will want to know the position of that image. Say the image has an ID of captionImage. You could gather its top, left position like this:
var imagePosition = $('#captionImage').offset();

The left position is stored in a property named left and the top position in a property name top:
imagePosition.top // number of pixels from the top of the document
imagePosition.left // number of pixels from the left edge of the document

For Example, You wanted to use this information to place a div with the id of caption - you could use jQuery’s .css() function to set the top, left, and position properties of the caption:
$('#caption').css({
'position' : 'absolute',
'left' : imagePosition.left,
'top' : imagePosition.top
});


The position() function returns an object containing the left and top position of an element from the top-left corner of its nearest positioned ancestor.

Difference between offset() and position() functions

The offset() and position() functions always return numbers representing the number of pixels from the left and top positions. That is, even if you use ems or percentages to place an element on a page, these two functions only retrieve the pixel position of the element.

Example
position() works just like offset, so the following code:
$('#outerBox').position() // { left : 100, top : 300 }

returns an object with a left property of 100 and a top property of 300, since those are the values set in the CSS.

You’ll get two different results for offset() and position():
$('#innerBox').offset() // { left : 300, top : 550 }
$('#innerBox').position() // { left : 200, top : 250 }

In this case, offset() returns the position in relationship to the document; that is, the inner box is 300 pixels from the left edge of the document and 550 pixels from its top. The position() function, on the other hand, returns the CSS left and CSS top properties for the div.

0 comments:

Post a Comment