I want to get the position of an element relative to the browser\'s viewport (the viewport in which the page is displayed, not the whole page). How can this be done in JavaS
jQuery implements this quite elegantly. If you look at the source for jQuery's offset
, you'll find this is basically how it's implemented:
var rect = elem.getBoundingClientRect();
var win = elem.ownerDocument.defaultView;
return {
top: rect.top + win.pageYOffset,
left: rect.left + win.pageXOffset
};