views:

118

answers:

2

Given an HTML DOM ID, how to get an element's position relative to the window in JavaScript/JQuery? This is not the same as relative to the document nor offset parent since the element may be inside an iframe or some other elements. I need to get the screen location of the element's rectangle (as in position and dimension) as it is currently being displayed. Negative values are acceptable if the element is currently off-screen (have been scrolled off).

This is for an iPad (WebKit / WebView) application. Whenever the user taps on a special link in an UIWebView, I am supposed to open a popover view that displays further information about the link. The popover view needs to display an arrow that points back to the part of the screen that invokes it.

Thanks

A: 

This sounds more like you want a tooltip for the link selected. There are many jQuery tooltips, try out jQuery qTip. It has a lot of options and is easy to change the styles.

Otherwise if you want to do this yourself you can use the jQuery .position(). More info about .position is on http://api.jquery.com/position/

$("#element").position(); will return the current position of an element relative to the offset parent.

There is also the jQuery .offset(); which will return the position relative to the document.

jhanifen
Its not really a tooltip, but to open a native UI widget to add annotations.
adib
+3  A: 
$(function() {
  var eTop = $('element').offset().top;
  console.log(eTop - $(window).scrollTop());

  $(window).scroll(function() {
     console.log(eTop  - $(window).scrollTop());
  });
});

You can give it a try here

Ninja Dude
Thanks for the script. This seems to work in the desktop but doesn't work on the iPad. It seems that $(window).scrollTop() and $(window).scrollLeft() doesn't get updated in the iPad. You can try my version via http://jsbin.com/ogiwu4/5/
adib
@adib, your code is just similar to my code =)
Ninja Dude
@avinash - my code is similar because its derived from yours ;-)
adib