jQuery get click element’s coordinates

1

How can I get clicked element’s coordinates that means mouse x and y positions related to the clicked element, related to document and related to it’s parent element?This is not the big task.jQuery pageX, pageY, offset() events can be use for this purpose. I’ll describe these all types, it’s usages and error handling.

So we’ll get the position of mouse pointer related to element or simply the mouse pointer location.

Get click element’s coordinates related to the element

Here is the html content.

Here is the css style.

Here is the jquery script to get the clicked position’s coordinates related to the element.

Explanation

Check this diagram.Then you can easily understand what am I saying above. 😉
NOTE: You must set the css styles in the element as position:relative.
jQuery get clicked element's-coordinates

Get clicked element’s coordinates related to the document

Now we’ll see how to get clicked position’s coordinates related to the document.Previously we discussed related to the element.
Here is the jquery script to get the clicked position’s coordinates related to the document.

Explanation

Get the clicked position's coordinates-related to the document

Get clicked element’s coordinates related to it’s parent element

Further explanations about offset() and position()

The .offset() method allows to retrieve the current position of an element related to the document.
.position(), which retrieves the current position related to the offset parent.

For a example, I have following html content.

The offset of the id named “subElement” is top:200 and left:200.But it’s the position is left:0 and top:0

But if you add attribute in the css position:relative; you can find the difference then.

.offset().top will get the top from the document.

.position().top will get the top from the relative parent.(if parent is relatively set)

Share.

About Author

Sumith Harshan is the Web Engineer Specializes in Java Script, JQuery, HTML4/5, CSS2/3, PHP, CodeIgniter, CakePHP, J2SE, J2EE, XML, Hacking & Security, Mobile Interface Developing, Magento, Wordpress, Joomla, Drupal,PHPBB,Facebook App Developing and Open cart...etc.

  • Lazar N.

    How do I just click the X – Y of an element inside a div ?