Fistright
Fistright

Reputation: 175

How does jquery find element's offset?

With jquery offset function we can find the coordinates of an element relative to the window.How does jquery do this?

Upvotes: 2

Views: 905

Answers (2)

traktor
traktor

Reputation: 19376

Jquery generally attempts to operate in a cross browser fashion, but it may help to understand some of the underlying options and principles.

Element.getBoundingClientRect() returns the size of an element and its position relative to the browser's viewport.

In reasonably modern browsers viewport and window dimensions can be interrogated using window.innerHeight and related (innerWidth, outerHeight, outerWidth) properties.

The coordinates of fixed position elements relative to the viewport can be obtained from interpreting their computed style values with respect to which viewport border the positioned element is relative.

Fall back options are to sum HTMLelement's offsetLeft and offsetTop values with those of all HTMLobjects in their offsetParent chain to calculate an element's cumulative offset within a rendered document, and then adjust calculated values for document's current X and Y scroll positions. MDN's article on window.scrollX gives an example of how to calculate scroll position in cross browser fashion.

This is intended as a set of documentation links for how jQuery code, or any other library or plain javascript code, might go about calculating window position. I have not attempted to investigate every browser bug the jQuery may quietly work around for you.

Upvotes: 3

Sami
Sami

Reputation: 3800

Might be you are looking for .offsetParent()

Offset Parent

Upvotes: -1

Related Questions