views:

33

answers:

1

I need to get the TOP and LEFT coordinates of the 5th paragraph on my page, or maybe the 6th paragraph, or the 8th, im just trying to figure out how to get the coordinates for any paragraph on the page I choose. I then need to insert a div 20px to the left of the top left of the paragraph i choose. Can anyone help?

+4  A: 

You can use .offset() for this, for example:

var offset = $("p:eq(4)").offset();
//top is offset.top
//left is offset.left

Or, if you need it to be more dynamic on the "which" paragraph, use .eq() like this:

$("p").eq(4).offset();

You can test it out here.

Nick Craver
If you're going to use `.offset()`, make sure you're also familiar with [`.position()`](http://api.jquery.com/position/) and how the two are different (position relative to document vs. position relative to offset parent, respectively).
Adam Backstrom
Doesn't work when trying to accomplish what I described. Here's a link to the updated code. Any ideas? Why isn't it showing up on the 3rd line? http://jsfiddle.net/AEfQP/2/
android.nick
It shows up on the 4th here (3 and 0-based index), what browser are you having issues in? You can also add/substract whatever values you need to move things around, for example: http://jsfiddle.net/nick_craver/AEfQP/3/
Nick Craver
is it possible for any kind of positioning on something else in the document to throw off the top and left numbers?
android.nick
@android.nick - There shouldn't be, are you placing the element inside a relatively positioned container?
Nick Craver
Yeah the element is inside a relatively positioned container. I finally discovered that i can get it to go into the correct position if I subtract the amount of pixels above the container, since i'm only positioning the Top, not the left. im trying to figure out why the number of pixels from the top of the window down to the relatively positioned container are being added to the top of the element i'm positioning, so it's pushing the element down too far, do you know why that is?
android.nick
AH! I reproduced the problem, so i think i need to have my element outside of the rel positioned container, otherwise when it's positioned it will add the amount of pixels from the top of the doc down to the top of itself. is that right? http://jsfiddle.net/AEfQP/6/
android.nick
@android.nick - Yup, that's correct, you want to use `.position()` instead of `.offset()` in this case, like this: http://jsfiddle.net/nick_craver/AEfQP/7/
Nick Craver