I need a popup div that will appear right below the anchor that i clicked. Now, I want to determine the x and y coordinates onClick event of an anchor. What's the best practice of doing it? What are the advisable event properties to use?
Asked
Active
Viewed 4.8k times
2 Answers
38
offsetX and offsetY are relative to the parent container, whereas pageX and pageY are relative to the document. Don't confuse this with .offset()
and .position()
, in which .offset()
is relative to the document and .position()
is relative to the parent container's .offset()
.
Something like this example should work (JQuery):
$('a').click(function(){
var offset = $(this).offset();
$('#popup_div').css('top',offset.top + 'px').css('left',offset.left + 'px').show();
});

ajon
- 7,868
- 11
- 48
- 86

AlienWebguy
- 76,997
- 17
- 122
- 145
-
1the docs here: (http://api.jquery.com/category/events/event-object/#post-850) seem to indicate that pageX/Y are relative to the document, not the window, which matters if the page has been scrolled. – aaronstacy Oct 30 '12 at 15:58
-
5The usage of jQuery is entirely superfluous to being able to answer this question. Believe it or not you *can* determine the x,y coordinates *without* requiring jQuery. – Neil Jun 26 '15 at 09:13
-
My guess is that El.pageY is the distance in pixels of an element from the top edge of the document, whatever content the document may have when last rendered. I'll test this to see if it works. The top edge of the document may not be visible if the window or content is scrolled. pageY would be zero at the very start of the document and would increase moving down to the current element. – David Spector Dec 06 '18 at 21:44
-
I was wrong. It turns out that the DOM/JavaScript designers did not provide a simple way to determine document position in all cases. A complicated calculation is needed, and it may not work. See https://stackoverflow.com/questions/5598743/finding-elements-position-relative-to-the-document . Finding position relative to certain nearest containing element and relative to the viewport are both easy. Wow, incredible. – David Spector Dec 06 '18 at 22:08
-
this answers is wrong AFAICT. First off the question is not tagged jquery and second according to [the spec](https://drafts.csswg.org/cssom-view/#dom-mouseevent-offsetx) offsetX and offsetY are not relative to any parent, they are relative to the target – gman May 19 '19 at 03:10
2
2 extracts from Jquery Documentation website
The .position() method allows us to retrieve the current position of an element relative to the offset parent
http://api.jquery.com/position/
The .offset() method allows us to retrieve the current position of an element relative to the document.

Martin Liversage
- 104,481
- 22
- 209
- 256

Praveen Prasad
- 31,561
- 18
- 73
- 106