Skip to content Skip to sidebar Skip to footer
Reading Time: 2 minutes

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.

1- Get click element’s coordinates related to the element

Here is the html content.

Content goes here

 

Here is the css style.

#myElement {
	height: 100px;
	position: relative; /* this is essential */
	width: 100px;
}

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

$(document).ready(function(e) {
    $('#myElement').click(function(e) {
        var posX = $(this).offset().left;// distance from left of the document
        var posY = $(this).offset().top; // distance from top of the document
        alert('left: '+(e.pageX - posX) + ' , top: ' + (e.pageY - posY));
    });
});

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 click element's coordinates

  

2- 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.

$(document).ready(function(e) {
    $('#myElement').click(function(e) {
         alert('left: '+e.pageX+ ' , top: '+ e.pageY);
    });
});

Explanation

jQuery get click element's coordinates
  

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

$(document).ready(function(e) {
  $('#myElement').click(function(e) {
        var posX = $(this).position().left;//related to it's parent element from left
        var posY = $(this).position().top; //related to it's parent element from top
        alert('left: '+(e.pageX - posX) + ' , top: ' + (e.pageY - posY));
  });
});

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.

xxx

 

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)

Read the common issue JQuery trigger click event not working.